控件的使用方法一般有兩種,一種是xml配置,一種是直接在java程序上調用。遊戲開發很少使用xml配置。
java代碼:
public void onCreate(Bundle savedInstanceState) {//回調方法
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//設置顯示的View
textView = (TextView) this.findViewById(R.id.textView);
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(this);//爲button添加監聽器
imageButton = (ImageButton) this.findViewById(R.id.imageButton);
imageButton.setOnClickListener(this);//爲imageButton添加監聽器
toggleButton = (ToggleButton) this.findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(this);//爲toggleButton添加監聽器
}
public void onClick(View v) {//重寫的事件處理回調方法
if(v == button){//點擊的是普通按鈕
textView.setText("您點擊的是普通按鈕");
}
else if(v == imageButton){//點擊的是圖片按鈕
textView.setText("您點擊的是圖片按鈕");
}
else if(v == toggleButton){//點擊的是開關按鈕
textView.setText("您點擊的是開關按鈕");
}
}
}
xml代碼:
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您沒有點擊任何按鈕" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="普通按鈕" />
<ImageButton android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img" />
<ToggleButton android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
輸出效果:
編寫過程遇到的問題主要是 每個文件,圖片名都要小寫。