Android onClick事件三种实现方法

来源:互联网 发布:支持的承载网络 编辑:程序博客网 时间:2024/05/22 01:34


 

 

 

8.    public class HelloActivity extends Activity {  

9.      

10.      /** Called when the activity is first created. */  

11.      @Override  

12.      public void onCreate(Bundle savedInstanceState) {  

13.          super.onCreate(savedInstanceState);  

14.          setContentView(R.layout.main);  

15.          Button btnMethod01;  

16.          Button btnMethod02;  

17.          Button btnMethod03;  

18.            

19.          btnMethod01 = (Button)findViewById(R.id.button1);  

20.          btnMethod02 = (Button)findViewById(R.id.button2);  

21.          btnMethod03 = (Button)findViewById(R.id.button3);  

22.            

23.          //第一种方法:匿名类  

24.          btnMethod01.setOnClickListener(new Button.OnClickListener(){  

25.    

26.              public void onClick(View v){  

27.                  Toast.makeText(HelloActivity.this,R.string.method01  

28.                          ,Toast.LENGTH_SHORT).show();  

29.              }  

30.                

31.          });  

32.            

33.          //添加监听事件  

34.          btnMethod02.setOnClickListener(new button1OnClickListener());  

35.      }  

36.      //第二种方法:内部类实现  有两部 1.写内部类 2.添加监听事件  

37.      private class button1OnClickListener implements OnClickListener{  

38.          public void onClick(View v){  

39.              Toast.makeText(HelloActivity.this,R.string.method02,  

40.                      Toast.LENGTH_SHORT).show();  

41.          }  

42.            

43.      }  

44.      //第三种方法:用xml方法配置,该名称要与  main.xml button03   

45.      //android:onClick="OnClickButton03"的名字一样  

46.      public void OnClickButton03(View v){  

47.          Toast.makeText(HelloActivity.this,R.string.method03  

48.                  ,Toast.LENGTH_SHORT).show();  

49.      }  

50.        

51.  }  

[html] view plaincopy

1.    <?xml version="1.0" encoding="utf-8"?>  

2.    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

3.        android:layout_width="fill_parent"  

4.        android:layout_height="fill_parent"  

5.        android:orientation="vertical">  

6.        <Button  

7.            android:id="@+id/button1"  

8.            android:layout_width="match_parent"  

9.            android:layout_height="wrap_content"  

10.          android:text="@string/method01"/>  

11.      <Button  

12.          android:id="@+id/button2"  

13.          android:layout_width="match_parent"  

14.          android:layout_height="wrap_content"  

15.          android:text="@string/method02"/>  

16.    

17.      <Button  

18.          android:onClick="OnClickButton03"  

19.          android:id="@+id/button3"  

20.          android:layout_width="match_parent"  

21.          android:layout_height="wrap_content"  

22.          android:text="@string/method03"/>  

23.    

24.  </LinearLayout>  

 

0 0