"Reading notes-the zero-start of Android game programming" 3.Android game development of common system controls (Button, Layout, ImageButton)

Source: Internet
Author: User

3.1 Button

button This control does not need to say more, is a button, mainly after the click to respond to the corresponding event.

Add id attribute to component: The definition format is android:id= "@+id/name", where name is custom, not index variable. "@+" represents a new declaration, "@" means a reference, for example:
"@+id/tv" means the new declaration of an ID, which is the component with the ID name TV;
"@id/tv" means a reference to a component with the ID name TV.

Add a Click event response to a button

If you want to know whether a button is clicked by a user, you need a "click listener" to listen to it, and then through the listener to get the click of the event, you can determine whether the button is clicked by the user.
There are two ways of using listeners:
1. The current class use Click Listener Interface, modified after the source code as follows:

//use a click Listener Public classButtonprojectextendsActivityImplementsOnclicklistener {PrivateButton Btn_submit,btn_cancel; PrivateTextView TV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.button_project_layout); Btn_submit=(Button) Findviewbyid (r.id.btn_submit); Btn_cancel=(Button) Findviewbyid (r.id.btn_cancel); TV=(TextView) Findviewbyid (r.id.tv); Btn_submit.setonclicklistener ( This); Btn_cancel.setonclicklistener ( This); }        //use the TAP listener to override its abstract function,//@Override represents an overriding function@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub        if(v = =btn_submit) {Tv.settext ("OK button trigger event!"); }Else if(v==btn_cancel) {Tv.settext ("Cancel button trigger event!" "); }    }}

First use the current class using the Click Listener Interface (onclicklistner), rewrite the Click Listener abstract Function (OnClick), and then the need to listen to the button button binding listener operation, so that the listener can monitor the binding button to determine whether it was clicked by the user, Once the button is clicked, it automatically responds to the OnClick function and passes in the clicked button (the button is also 1 views), and then writes the click-triggered event in the onclick function (because multiple buttons are defined, So in the OnClick function to the system in the view of the button to match the judgment, so that different buttons do not handle the event).

2. Use the internal class to implement the listener to listen, the modified source code is as follows:

 Public classButtonprojectextendsActivity {PrivateButton Btn_submit,btn_cancel; PrivateTextView TV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.button_project_layout); Btn_submit=(Button) Findviewbyid (r.id.btn_submit); Btn_cancel=(Button) Findviewbyid (r.id.btn_cancel); TV=(TextView) Findviewbyid (r.id.tv); //to bind the Btn_submit button to a point-click ListenerBtn_submit.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method StubTv.settext ("OK button trigger event!"));        }        }); Btn_cancel.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubTv.settext ("Cancel button trigger event! ");    }        }); }}

In the form of an inner class, you also need to rewrite the listener's abstract function and then handle the event in the onclick, where you don't have to judge the view because a button corresponds to a listener.


Button Class Official document address : http://developer.android.com/reference/android/widget/Button.html

It is stated that you can now use the Android:onclick property in an XML Layout button control without onclicklistener the listener. You then invoke the OnClick method that you set in the class. The code is as follows:

< Button      Android:layout_height = "Wrap_content"      android:layout_width= "Wrap_content"     android:text= "@string/self_ Destruct "     android:onclick=" selfdestruct "/>

When the user clicks the button, the Android system calls the Selfdestruct method. The method must be public and accept a view as its only parameter.

 Public void selfdestruct (view view) {     //  button response event }

3.2 Layout

1. Linear Layout LinearLayout

LinearLayout Official document address:http://developer.android.com/reference/android/widget/LinearLayout.html

LinearLayout (linear layout) is one of the most commonly used layouts in 5, which, by default, maintains the interval of components and the alignment of components to each other (right, middle, or left-aligned relative to one component) when the component is displayed. The linear layout displays the components in both vertical and horizontal ways, which can be set by Orienrarion.
The Orientation property represents the orientation of the controls in the layout, with two property values, one for the "vertical" vertical arrangement (see left) and the other for the "horizontal" horizontal arrangement (see right).

(1) Gravity: Each component defaults to its top-left alignment, and its properties can adjust the alignment of components, such as left, right, or center alignment.
(2) padding: Padding of margin, also known as inner margin. The margin properties are:
Android:paddingtop, set the top margin;
Android:paddingbottom, set the bottom margin;
Android:paddingleft, set the left margin;
Android:paddingright, set the right margin;
Android:padding is a uniform adjustment of the inner margins around the four direction.
The margin property value is a specific number.
(3) Layout_margn: Margin, the upper and lower left and right margin properties are similar to the padding.

The padding padding refers to the margin between the current layout and the contained components, and the layout_margn margin refers to the margin between the other components.

2. Relative Layout relativelayout

Relativelayout Official document Address: http://developer.android.com/reference/android/widget/RelativeLayout.html

Relativelayout (relative layout): In addition to the most commonly used linearlayout, relative layout is another common layout. Unlike linear layouts, a linear layout requires that all components be aligned if one component needs to be aligned to another component, or that a nested layout is used, but relative layouts do not have to be so cumbersome. Because in a relative layout, each component can specify a location relative to another component or parent component, but must be specified by ID. Modify the Main.xml layout as follows;

So in a relative layout, if you want to fix the position of a component, at least determine the component's position in the "left and right" and "up" two positions to accurately fix the component.

3. Table Layout Tablelayout

Tablelayout Official document address:http://developer.android.com/reference/android/widget/TableLayout.html

Tablelayout (table layout) is styled like a table. Typically, Tablelayout has multiple TableRow, each TableRow is a row, defining several TableRow is defining a few lines: Tablelayout does not display the row and column numbers, and there are no split lines. Its number of rows and columns has its own operation and determination.
Here are a few of the properties that are commonly used in Tablelayout:
(1) Shrinkcolumns property: 0 is the order, when the TableRow inside the control is full of layout, the specified column automatically extends to fill the available parts, when the TableRow inside the control is not covered with layout, does not work.
(2) Strechcolumns property: Specifies the column to fill the blank part with the No. 0 action order.
(3) Collapsecolumns property: Hides the specified column in the No. 0 action order.
(4) Layout_column property: Sets the component to display in the specified column in the No. 0 action order.
(5) Layout_span property: Sets the number of columns occupied by the component display in the No. 0 action order.

4. Absolute layout absolutelayout

Absolutelayout Official document address:http://developer.android.com/reference/android/widget/AbsoluteLayout.html

Absolutelayout (absolute layout) layout usage, such as its name, the location of the component can accurately specify its x/Y coordinate position on the screen. Although can be precise to specify the coordinates, but because the code is too rigid to write, so that in different devices, different resolutions of mobile devices on the mobile device can not be very good to show the effect, this layout set component location is adjusted with X/Y, but also make the overall layout format code is very inflexible, so this layout is not recommended for use.

5. Single Frame layout framelayout

Framelayout Official document address:http://developer.android.com/reference/android/widget/FrameLayout.htm

Framelayout (single frame layout) is the simplest of layouts in 5 because a single frame layout always places components in the upper-left corner of the screen when a new component is defined, even if multiple components are defined in the layout, and the latter component always overwrites the previous component unless the last component is transparent.

3.3 ImageButton

ImageButton Official document address:http://developer.android.com/reference/android/widget/ImageButton.html

ImageButton is similar to button, except that ImageButton can customize a picture as a button, and because the use of a picture instead of a button, ImageButton pressing and lifting the style effect needs to be customized.

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >    <ImageButtonAndroid:id= "@+id/btn_imagebutton"Android:layout_marginleft= "100DP"Android:layout_margintop= "100DP"Android:layout_width= "100DP"Android:layout_height= "100DP"Android:background= "@drawable/dsfvsdf" /></LinearLayout>
 Public classImagebuttonprojectextendsActivity {PrivateImageButton Btn_imagebutton; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);                Setcontentview (r.layout.imagebutton_layout); Btn_imagebutton=(ImageButton) Findviewbyid (R.id.btn_imagebutton); //Add touch screen monitoring for picture buttonsBtn_imagebutton.setontouchlistener (NewOntouchlistener () {@Override//First parameter: Represents the event source that triggered the touch-screen event View//Second parameter: Indicates the type of touch event, such as press, lift, move, etc.              Public BooleanOnTouch (View V, motionevent event) {//TODO auto-generated Method Stub                if(Event.getaction () ==motionevent.action_down)//Press the event                {                    //Set Picture button background//getresources (). getdrawable (int id) the incoming picture ID gets a drawable object. btn_imagebutton.setbackgrounddrawable (Getresources (). getdrawable (R.DRAWABLE.DSFVSDF_BG)); }Else if(Event.getaction () ==motionevent.action_up)//Lift Up Event{btn_imagebutton.setbackgrounddrawable (Getresources (). Getdrawable (R.drawable.dsfvs                DF)); }                return false;    }        }); }}

Show different button status The official documentation mentions can be configured separately in the XML file and then referenced in the layout file as follows:

<?XML version= "1.0" encoding= "Utf-8"?> <selectorxmlns:android= "Http://schemas.android.com/apk/res/android">     <Itemandroid:state_pressed= "true"android:drawable= "@drawable/button_pressed" /> <!--pressed Press the status -     <Itemandroid:state_focused= "true"android:drawable= "@drawable/button_focused" /> <!--focused Focus State -     <Itemandroid:drawable= "@drawable/button_normal" /> <!--Default state Defaults - </selector>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.