onClickListener的设置
- 在控件里面声明
- 通过查找id的方式找到控件,然后再设置点击事件
此处可以有两种设置方式。
<Button
android:id="@+id/bt_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button1"
tools:layout_editor_absoluteX="157dp"
tools:layout_editor_absoluteY="99dp"
tools:ignore="MissingConstraints" />
<Button
android:id="@+id/bt_test2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button2"
tools:layout_editor_absoluteX="157dp"
tools:layout_editor_absoluteY="195dp"
tools:ignore="MissingConstraints" />
然后setOnClickListener
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mbt_test1;
private Button mbt_test2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initClickListener();
}
private void initClickListener() {
//方法一
mbt_test1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("test1 be clicked!");
}
});
//方法二
mbt_test2.setOnClickListener(this);
}
//寻找资源控件
private void initView() {
mbt_test1=findViewById(R.id.bt_test1);
mbt_test2=findViewById(R.id.bt_test2);
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
int id=v.getId();
switch (id){
case R.id.bt_test2:
System.out.println("test2");
break;
}
}
}