一,增加一个button并用外部类绑定事件
//XML文件: <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:text="扣子1" /> //主类: public class MainActivity extends Activity { private Button btn1 = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button)findViewById(R.id.button1); btn1.setOnClickListener(new buttonclick()); //方法一,定义外部类来绑定事件 class buttonclick implements OnClickListener { public void onClick(View arg0) { System.out.printline("点击了button1"); } }二,用内部类绑定事件
<span style="color: rgb(51, 51, 51);">btn1.setOnClickListener(new OnClickListener() { //方法二,定义</span><span style="color:#ff0000;"><strong>内部类</strong></span><span style="color: rgb(51, 51, 51);">来绑定事件 @Override public void onClick(View arg0) { //用Toast来显示提示 </span><span style="color:#ff0000;"><strong>//注意:Toast.makeText(Context context, CharSequence text, int duration)</strong></span><span style="color: rgb(51, 51, 51);"> </span><span style="color:#ff0000;"><strong>//context要指向主类自己,这个要弄明确!!!!,text设置文本,duration设置时间</strong></span><span style="color:#333333;"> Toast.makeText(getApplicationContext(), "click!", Toast.LENGTH_LONG).show(); } });</span>三,有多个button,将内部类设置成变量使代码更友好
xml文件就不多说了,
<span style="color:#333333;">private Button btn1 = null; private Button btn2 = null; btn1 = (Button)findViewById(R.id.button1); btn2 = (Button)findViewById(R.id.button2); btn1.setOnClickListener(listener); //有多个button btn2.setOnClickListener(listener); private OnClickListener listener =new OnClickListener() { //定义一个变量来装这个内部类 @Override public void onClick(View v) { </span><span style="color:#ff0000;"><strong>//注意View是什么,然后以下为什么要强制转换成button!!</strong></span><span style="color:#333333;"> Button btn = (Button)v; switch (btn.getId()) { case R.id.button1: Toast.makeText(getApplicationContext(), "click1!", Toast.LENGTH_LONG).show(); break; case R.id.button2: Toast.makeText(getApplicationContext(), "click2!", Toast.LENGTH_LONG).show(); break; } } };</span>