事件绑定采用setOnClickListener方法绑定事件
setOnClickListener
setOnClickListener为一个接口。传统事件绑定有如下几种方式:
-
1、匿名内部类监听
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("我被点击了");
}
});
}
}
-
2、外部类监听
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button3 = findViewById(R.id.button3);
btn3.setOnClickListener(new MyOnClickListener(){
@Override
public void onClick(View v) {
super.onClick(v);
Toast.makeText(MainActivity.this,"按钮被点击了",Toast.LENGTH_SHORT).show();
}
});
}
}
// 定义外部类实现OnClickListener接口实现监听
class MyOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
v.setAlpha(0.6f); //所有点击事件均会触发该事件,可通过此方法设置共通事件
}
}
-
3、接口方式监听
// MainActivity方法实现OnClickListener接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn3 = findViewById(R.id.button3);
btn3.setOnClickListener(this);
Button btn4 = findViewById(R.id.button4);
btn4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button3:
System.out.println("button3被点击");
break;
case R.id.button4:
System.out.println("button4被点击");
break;
}
}
}
网友评论