点击事件的写法
内部实现onclickListener的接口
public class LinearLayoutActivity extends Activity {
private Button bt_01;
private Button bt_02;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear);
bt_01 = (Button) findViewById(R.id.bt_01);
bt_02 = (Button) findViewById(R.id.bt_02);
bt_01.setOnClickListener(clickListener);
bt_02.setOnClickListener(clickListener);
}
private OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_01:
clickButton01();
break;
case R.id.bt_02:
// click button 02
break;
}
}
};
private void clickButton01() {
// click button 01
}
}
匿名内部类实现onclickListener
public class LinearLayoutActivity extends Activity implements OnClickListener{
private Button button = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear);
button = (Button) findViewById(R.id.b1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//do something
}});
}
}
让当前的Activity实现onclickListener的接口
界面的按钮较多,1,2两种代码会比较臃肿
public class LinearLayoutActivity extends Activity implements OnClickListener{
private Button button = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear);
button = (Button) findViewById(R.id.b1);
button.setOnClickListener(this);
}
public void onClick(View v) {
//do something
}
}
在布局xml文件里面声明onclick属性
属性里的""包含的是java代码里方法名(一般不推荐使用这个)
Activity:
public class LinearLayoutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear);
}
public void clickButton(View v) {
Intent intent = new Intent(this, RelativeLayoutActivity.class);
startActivity(intent);
}
}
Layout:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clickButton"
android:text="button" />