1、匿名内部类
Button btn_1 = (Button) findViewById(R.id.btn_1); //1.匿名内部类 btn_1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.i("匿名内部类", "点击事件"); } });
2、主类中(Activity活动)实现View.OnClickListener接口。在Activity活动中覆写OnClick(View view)方法。用Switch的view.getId()区别不同的Button的操作。
public class FirstActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_button); btn1 = (Button) findViewById(R.id.button1); btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(this); btn2.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: Toast.makeText(this, "111111111", Toast.LENGTH_SHORT).show(); break; case R.id.button2: Toast.makeText(this, "222222222", Toast.LENGTH_SHORT).show(); break; default: break; } } }
3、创建内部类,实现View.OnClickListener接口。
public class FirstActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_button); Button btn1 = (Button) findViewById(R.id.button1); Button btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(new MyClickListener()); btn2.setOnClickListener(new MyClickListener()); }
class MyClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: Toast.makeText(TestButtonActivity.this, "111111111", Toast.LENGTH_SHORT).show(); break; case R.id.button2: Toast.makeText(TestButtonActivity.this, "222222222", Toast.LENGTH_SHORT).show(); break; default: break; } } }
}
4、在布局文件中为该View设置android:onClick属性指定点击的方法名。此时,将点击事件的事件名交给了视图,告诉它该控件遇到点击时间时候要依据哪个函数。
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="Button1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="Button2" />
public class FIrstActivityextends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); } // 注意 这里没有 @Override 标签 这个是自定义的方法,和XML中的onClick后面的onClick属性一致 public void onClick(View v) { switch (v.getId()) { case R.id.button1: Toast.makeText(this, "111111111", Toast.LENGTH_SHORT).show(); break; case R.id.button2: Toast = Toast.makeText(this, "222222222", Toast.LENGTH_SHORT).show(); break; default: break; } } }
完。
时间: 2024-11-06 17:47:42