Android 開發之onClick事件的三種寫法

package a.a;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AActivity extends Activity {
	/** Called when the activity is first created. */

	EditText Ev1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Ev1 = (EditText)findViewById(R.id.editText1);  

		//第一種方式  
		Button Btn1 = (Button)findViewById(R.id.button1);//獲取按鈕資源  
		Btn1.setOnClickListener(new Button.OnClickListener(){//創建監聽  
			public void onClick(View v) {  
				String strTmp = "點擊Button01";  
				Ev1.setText(strTmp);  
			}  

		});  

		//第二種方式  
		Button Btn2 = (Button) findViewById(R.id.button2);//獲取按鈕資源  
		Btn2.setOnClickListener(listener);//設置監聽  

	}

	Button.OnClickListener listener = new Button.OnClickListener(){//創建監聽對象  
		public void onClick(View v){  
			String strTmp="點擊Button02";  
			Ev1.setText(strTmp);  
		}  

	};


	//第三種方式(Android1.6版本及以後的版本中提供了)  
	public void Btn3OnClick(View view){  
		String strTmp="點擊Button03";
		Ev1.setText(strTmp);

	}  
}


 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2" />
    
 <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button3" 
        android:onClick="Btn3OnClick"/>

 <EditText
     android:id="@+id/editText1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" >

     <requestFocus />
 </EditText>

</LinearLayout>


 

發佈了75 篇原創文章 · 獲贊 16 · 訪問量 111萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章