总结一下Button 点击事件onclick实现的四种方式;
方式一:
在xml中定义onclick属性
在Activity中创建onclick_button1方法
// 方式一 public void onclick_button1(View view) { Toast.makeText(this, “方式一”, Toast.LENGTH_SHORT).show(); }
方式二:
匿名内部类
button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, “方式二”, Toast.LENGTH_SHORT) .show(); } });
方式三:
创建内部类实现OnClickListener接口
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(new Button3()); } // 方式三 public class Button3 implements OnClickListener { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, “方式三”,
Toast.LENGTH_SHORT).show(); } }
方式四:
Activity实现OnClickListener接口
public class MainActivity extends Activity implements OnClickListener { Button button4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button4 = (Button) findViewById(R.id.button4); button4.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button4: Toast.makeText(MainActivity.this, “方式四”, Toast.LENGTH_SHORT).show(); break; default: break; } }}
————————————————