1.XML檔案中初始化
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/EditText1"
android:layout_below="@id/EditText1"
android:layout_marginTop="17dp"
android:text="一按就知道" />
android:id="@+id/ImageButton1"
android:layout_below="@id/button1"
android:layout_marginTop="17dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
2.java檔案中
final Button button = (Button)findViewById(R.id.button1);
button.setBackgroundColor(Color.rgb(0, 0, 255));
ImageButton imagebutton = (ImageButton)findViewById(R.id.ImageButton1);
imagebutton.setImageResource(R.drawable.aaa);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
button.setText("你按啦!");
button.setBackgroundColor(Color.rgb(255,112,112));
}
}); //寫在oncreate裡面
注意:
(1)添加的監聽器依然寫在oncreate函數中
(2)button前面使用final關鍵字修飾,否則出錯。
在使用Java局部内部類或者匿名内部類時,若該類調用了所在方法的局部變量,則該局部變量必須使用final關鍵字來修飾,否則将會出現編譯錯誤“Cannot refer to a non-final variable * inside an inner class defined in a different method”
final關鍵字:修飾類,表示這個類不能被繼承;
修飾方法,将方法鎖定,以防任何繼承類修改它的含義;
修飾變量,如果是基本資料類型的變量,值初始化後就不能修改,如果是引用類型變量,初始化後不能指向其他對象。
3.兩個按鈕注冊到一個監聽器上
@Override
public void onClick(View v){
switch(v.getId()){
case R.id.button1:
button.setText("哈哈,你按我啦!");
editText1.setText("button");
return;
case R.id.ImageButton1:
button.setText("你按我呀~");
editText1.setText("imagebutton");
return;
}
}
};
button.setOnClickListener(buttonListener);
imagebutton.setOnClickListener(buttonListener);
注意:最後兩句為将該監聽器分别注冊到兩個按鈕上。
初始化

點選button
點選imagebutton