Why declare buttons in onCreate() in MainActivity.java?

妖精的绣舞 提交于 2019-12-08 09:06:57

问题


I'm a noob in writing Android app.
The below 2 examples about declaring buttons are all from the Android developer site. (So both of them should be correct and working.)

Example 1: from http://developer.android.com/training/basics/firstapp/building-ui.html

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />

Example 2: from http://developer.android.com/guide/topics/ui/declaring-layout.html#attributes

<--! (In xml file) Define a view/widget in the layout file and assign it a unique ID: -->
<Button android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/my_button_text"/>


//(In java file) Then create an instance of the view object and capture it from the layout (typically in the onCreate() method):
Button myButton = (Button) findViewById(R.id.my_button);

1) So when would I want to assign "Android:id" for my button?

2) What would happen if I assigned "Android:id" for my button in the xml file but I did not declare the button in the "onCreate()" in "MainActivity.java"?


回答1:


Android:id is just an identifier for your element, in your case its Button. It will not do anything if you didnt use it in the onCreate method. The Id will be useful when you create any listener for the Button. ie., telling your what to do when it is clicked.

You will use something like this.

        Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
            }
        });



回答2:


Let's go over a few things really quick.

android:id is exactly what it sounds like, its an identification that is used to specify certain Views. Let's say for example you have two buttons on a single layout and you want the buttons to do certain things or maybe you just want to change the text of a button. You would need to initialize the buttons in your Activity onCreate method to do things with them through code. The id is used to differentiate between the views. In our two button example you might give one button the id of buttonOne and the other buttonTwo. This way Android knows which button you are talking about when you refer to them in code. If you assign an id to a button in XML and don't refer to it in code than the button simply does nothing. If you need more info on initializing Views than check out this post on my website. I'm fairly new to Android too so I can explain things to you in a way that you can understand =]

http://www.androidianlabs.com/android-basics-lesson-one.html



来源:https://stackoverflow.com/questions/13374125/why-declare-buttons-in-oncreate-in-mainactivity-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!