天天看點

android學習(1) - Button單擊事件的響應

通過Eclipse可以在自己的應用程式中增加一個按鈕,同時在main.xml中會自動增加如下的代碼:

---

[html]  view plain copy

  1. <Button  
  2.     android:id="@+id/button1"  
  3.     android:layout_width="wrap_content"  
  4.     android:layout_height="wrap_content"  
  5.     android:text="Button" />  

編譯運作程式時,将會看到一個按鈕。單擊它時,沒有任何的響應和動作。

需要我們手動增加代碼為該按鈕增加單擊事件的響應。

為按鈕增加單擊事件的響應時有兩種方式:

1、通過Button的setOnClickListener方法為該按鈕綁定一個單擊事件監聽器,用于監聽使用者的單擊事件。代碼如下:

[java]  view plain copy

  1. public class MyActivity extends Activity {  
  2.     protected void onCreate(Bundle icicle) {  
  3.         super.onCreate(icicle);  
  4.         setContentView(R.layout.content_layout_id);  
  5.         //手工增加代碼開始  
  6.         //将按鈕綁定一個單操作的事件監聽器。用于監聽使用者的單擊操作。  
  7.         final Button button = (Button) findViewById(R.id.button_id);  
  8.         button.setOnClickListener(new View.OnClickListener() {  
  9.             public void onClick(View v) {  
  10.                 // Perform action on click  
  11.                 //增加自己的代碼......  
  12.                 final TextView text = (TextView) findViewById(R.id.textView1);  
  13.                 text.setText("OnClick. " + " ....");      
  14.             }  
  15.         });  
  16.         //手工增加代碼結束  
  17.     }  
  18. }  

上面的代碼很簡短,但不利于閱讀。也可以使用下面的書寫方式:

[java]  view plain copy

  1. public class MyActivity extends Activity {  
  2.     protected void onCreate(Bundle icicle) {  
  3.         super.onCreate(icicle);  
  4.         setContentView(R.layout.content_layout_id);  
  5.         //手動增加代碼開始  
  6.         Button button = (Button) findViewById(R.id.button_id);  
  7.         button.setOnClickListener(myOnClickListener);  
  8.         //手動增加代碼結束  
  9.     }  
  10.    //手動增加代碼開始  
  11.    private OnClickListener myOnClickListener = new OnClickListener() {  
  12.        public void onClick(View v) {  
  13.        //增加自己的代碼......  
  14.        final TextView text = (TextView) findViewById(R.id.textView1);  
  15.        text.setText("OnClick. " + " ....");              
  16.        }         
  17.    };  
  18.    //手動增加代碼結束  
  19. }  

2、通過修改main.xml中Button的屬性,為按鈕增加單擊事件請求。修改的xml檔案如下:

[html]  view plain copy

  1. <Button  
  2.     android:id="@+id/button1"  
  3.     android:layout_width="wrap_content"  
  4.     android:layout_height="wrap_content"  
  5.     android:onClick="OnMySelfClick"  
  6.     android:text="Button" />  

然後在.java檔案中增加xml檔案中提到的OnMySelfClick函數:

[java]  view plain copy

  1. public class HelloAndroidActivity extends Activity {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.main);   
  6.     }  
  7.     public void OnMySelfClick(View v)  
  8.     {  
  9.         final TextView text = (TextView) findViewById(R.id.textView1);  
  10.         text.setText("OnMySelfClick. " + " ....");      
  11.     }  
  12. }  

第二種方法比較第一種方法簡單了許多。

繼續閱讀