为什么在MainActivity.java中声明onCreate()中的按钮?

时间:2012-11-14 06:37:59

标签: android android-button

我是编写Android应用程序的小伙子 以下关于声明按钮的2个示例均来自Android开发人员站点。 (所以他们两个都应该是正确和有效的。)

示例1:来自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" />

示例2:来自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)那么我什么时候想为我的按钮分配“Android:id”?

2)如果我在xml文件中为我的按钮分配了“Android:id”但是我没有在“MainActivity.java”中的“onCreate()”中声明按钮会怎么样?

2 个答案:

答案 0 :(得分:1)

Android:id只是元素的标识符,在你的情况下是它的Button。如果你没有在onCreate方法中使用它,它将不会做任何事情。在为Button创建任何侦听器时,Id将非常有用。即,告诉你点击它时该做什么。

你会使用这样的东西。

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

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

答案 1 :(得分:0)

让我们快点回顾一些事情。

android:id就是它听起来的样子,它是一个用于指定某些视图的标识。比方说,例如,您在一个布局上有两个按钮,您希望按钮执行某些操作,或者您只是想更改按钮的文本。您需要初始化Activity onCreate方法中的按钮,以便通过代码对它们执行操作。 id用于区分视图。在我们的两个按钮示例中,您可以为一个按钮指定buttonOne的id和另一个buttonTwo的id。这样,当您在代码中引用它们时,Android就知道您正在谈论哪个按钮。如果您为XML中的按钮分配一个id,而不是在代码中引用它,那么按钮就什么都不做。如果您需要有关初始化视图的更多信息,请在我的网站上查看此帖子。我也是Android的新手,所以我可以用你能理解的方式向你解释=]

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