我是编写Android应用程序的noob。
以下有关声明按钮的2个示例全部来自Android开发人员网站。 (所以他们都应该是正确的和工作。)为什么要在MainActivity.java中的onCreate()中声明按钮?
例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()”中声明按钮,会发生什么?
您将该按钮分配给onCreate中的变量,以便您可以附加事件处理程序和事件,如果不这样做,那么您只需要一个不执行任何操作的按钮。 – TheZ
嗨TheZ:你是什么意思的事件处理程序?如果你在点击按钮时意味着这个动作,那么代码只需在java文件中编写一个“sendMessage()”动作监听器来处理这个动作,它就可以工作。 – Sean
当然,你可以使用布局xml来分配一个onClick(事实上,Google已经做得很好,几乎所有的选项都可以通过xml获得),但是有时你需要(例如)激活/停用动态按钮 – TheZ