The onCreate(Bundle) method is called when an instance of the activity subclass is created. 'When an activity is created, it needs a user interface to manage.
To get the activity its user interface, you call the following Activity method:
public void setContentView(int layoutResID)
ex:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
說明:
setContentView: 設定連結layout的resource ID
設定layout上widget的resource ID:
(只有需要控制的才需設定)
利用android:id="@+id/名稱"
ex:
activity_main.xml:
<Button
android:id="@+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/true_button" />
<Button
android:id="@+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/false_button" />
->
R.java:
public static final class id {
public static final int action_settings=0x7f080002;
public static final int false_button=0x7f080001;
public static final int true_button=0x7f080000;
}
從程式存取XML裡設定的widget:
利用resource id找到widget
Button mTrueButton = (Button)findViewById(R.id.true_button);
建立activity和顯示activity的流程:
1. 新增activity的類別 (.java檔)
2. 新增activity對應的layout (.xml檔)
3. 設計activity的layout ( .xml 檔)
4. 於activity的java檔連結xml
ex:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_period);
}
5. 於AndroidManifest.xml加入activity
ex:
<activity
android:name=".AddPeriodActivity"
android:label="@string/app_name" >
</activity>
6. 顯示activity
ex:
Intent intent = new Intent(this, AddPeriodActivity.class);
this.startActivity(intent);
沒有留言:
張貼留言