为什么要在MainActivity.java的onCreate()中声明按钮? [英] Why declare buttons in onCreate() in MainActivity.java?

查看:384
本文介绍了为什么要在MainActivity.java的onCreate()中声明按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编写Android应用程序的菜鸟.
以下有关声明按钮的2个示例均来自Android开发人员网站. (因此,它们两个都应该正确且可以正常工作.)

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.)

示例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"?

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

2)如果我在xml文件中为按钮分配了"Android:id",但是没有在"MainActivity.java"的"onCreate()"中声明该按钮,将会发生什么情况?

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"?

推荐答案

Android:id只是元素的标识符,在您的情况下是Button的标识符.如果您没有在onCreate方法中使用它,它将不会执行任何操作.当您为Button创建任何侦听器时,Id将很有用.也就是说,告诉您单击该怎么办.

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
            }
        });

这篇关于为什么要在MainActivity.java的onCreate()中声明按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆