步骤:
1.获取代表控件对象。
2.定义一个类,实现监听接口。
3.生成监听器对象。
4.为控件绑定监听器对象。
XML
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context=".MainActivity" > 10 11 <TextView 12 android:id="@+id/textview" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="@string/hello_world" /> 16 17 <Button 18 android:id="@+id/btn" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" 21 android:text="button" 22 /> 23 24 </LinearLayout>
Java
1 package com.ibox365.testnew; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.util.Log; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.TextView; 10 11 public class MainActivity extends Activity { 12 final static String Tag="com.ibox365.testnew"; 13 private Button button; 14 private TextView textView; 15 int count=0; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 22 button=(Button) findViewById(R.id.btn); 23 textView=(TextView) findViewById(R.id.textview); 24 25 ButtonListen buttonListen=new ButtonListen(); 26 button.setOnClickListener(buttonListen); 27 28 } 29 30 class ButtonListen implements OnClickListener{ 31 32 /* (non-Javadoc) 33 * @see android.view.View.OnClickListener#onClick(android.view.View) 34 */ 35 @Override 36 public void onClick(View v) { 37 // TODO Auto-generated method stub 38 count++; 39 textView.setText(count+""); 40 Log.i(Tag, "点击次数为:"+count+""); 41 } 42 43 44 } 45 46 47 }