我是編寫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