通過Eclipse可以在自己的應用程式中增加一個按鈕,同時在main.xml中會自動增加如下的代碼:
---
[html] view plain copy
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" />
編譯運作程式時,将會看到一個按鈕。單擊它時,沒有任何的響應和動作。
需要我們手動增加代碼為該按鈕增加單擊事件的響應。
為按鈕增加單擊事件的響應時有兩種方式:
1、通過Button的setOnClickListener方法為該按鈕綁定一個單擊事件監聽器,用于監聽使用者的單擊事件。代碼如下:
[java] view plain copy
- 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. " + " ....");
- }
- });
- //手工增加代碼結束
- }
- }
上面的代碼很簡短,但不利于閱讀。也可以使用下面的書寫方式:
[java] view plain copy
- 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檔案如下:
[html] view plain copy
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:onClick="OnMySelfClick"
- android:text="Button" />
然後在.java檔案中增加xml檔案中提到的OnMySelfClick函數:
[java] view plain copy
- public class HelloAndroidActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
- public void OnMySelfClick(View v)
- {
- final TextView text = (TextView) findViewById(R.id.textView1);
- text.setText("OnMySelfClick. " + " ....");
- }
- }
第二種方法比較第一種方法簡單了許多。