通過Eclipse可以在自己的應用程式中增加一個按鈕,同時在main.xml中會自動增加如下的代碼:
---
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />
編譯運行程式時,將會看到一個按鈕。單擊它時,沒有任何的響應和動作。
需要我們手動增加代碼為該按鈕增加單擊事件的響應。
為按鈕增加單擊事件的響應時有兩種方式:
1、通過Button的setOnClickListener方法為該按鈕綁定一個單擊事件監聽器,用於監聽使用者的單擊事件。代碼如下:
public class MyActivity extends Activity { protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.content_layout_id); //手工增加代碼開始 //將按鈕綁定一個單操作的事件監聽器。用於監聽使用者的單擊操作。 final Button button = (Button) findViewById(R.id.button_id); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click //增加自己的代碼...... final TextView text = (TextView) findViewById(R.id.textView1); text.setText("OnClick. " + " ...."); } }); //手工增加代碼結束 } }
上面的代碼很簡短,但不利於閱讀。也可以使用下面的書寫方式:
public class MyActivity extends Activity { protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.content_layout_id); //手動增加代碼開始 Button button = (Button) findViewById(R.id.button_id); button.setOnClickListener(myOnClickListener); //手動增加代碼結束 } //手動增加代碼開始 private OnClickListener myOnClickListener = new OnClickListener() { public void onClick(View v) { //增加自己的代碼...... final TextView text = (TextView) findViewById(R.id.textView1); text.setText("OnClick. " + " ...."); } }; //手動增加代碼結束 }
2、通過修改main.xml中Button的屬性,為按鈕增加單擊事件請求。修改的xml檔案如下:
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="OnMySelfClick" android:text="Button" />
然後在.java檔案中增加xml檔案中提到的OnMySelfClick函數:
public class HelloAndroidActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } /* ************************************ * 按鈕的單擊操作處理函數。 * 下面的函數是一個按鈕單擊的處理函數。 * 它需要在layout的xml中將按鈕增加一個OnClick的屬性, * 並指定它的處理函數。如下 * * android:onClick="OnMySelfClick" * * 這樣的話,就不用再增加上面那些複雜的代碼了。 * * */ public void OnMySelfClick(View v) {final TextView text = (TextView) findViewById(R.id.textView1);text.setText("OnMySelfClick. " + " ...."); }}
第二種方法比較第一種方法簡單了許多。