Android点击事件大概可以分为以下几种:
- 匿名内部类
- 用Activity实现OnClickListener接口
- 指定控件的onClick的属性
匿名内部类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("匿名内部类", "点击事件");
}
});
}
定义内部类,实现OnClickListener接口
public class MainActivity extends Activity implements OnClickListener {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Log.i("用Activity实现OnClickListener接口", "点击事件");
}
}
指定控件的onClick的属性
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="点击事件" />
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v) {
Log.i("指定onClick属性方式","点击事件");
}
}