android studio按钮监听的5种方法实例详解

1.匿名内部类

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = findViewById(R.id.btn1);//匿名内部类
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), “你点击了按钮1”, Toast.LENGTH_LONG).show();
}
});
}

2.内部类

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn2 = findViewById(R.id.btn2);
Btn2CLickListener btn2CLickListener = new Btn2CLickListener();
btn2.setOnClickListener(btn2CLickListener);
}
class Btn2CLickListener implements View.OnClickListener{
@Override
public void onClick(View v){
Toast.makeText(getApplicationContext(),“你点击了按钮2”,Toast.LENGTH_LONG).show();
}
}

3外部类**

MainActivity.java:

public class MainActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Button btn3 = findViewById(R.id.btn3);
Btn3ClickListener btn3CLickListener = new Btn3ClickListener(getApplicationContext());
btn3.setOnClickListener(btn3CLickListener);
}

Btn3ClickListener.java:

4自身activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn4 = findViewById(R.id.btn4);//main activity
btn4.setOnClickListener(this);
}

public void onClick(View v) {
Toast.makeText(getApplicationContext(), “你点击了按钮4”, Toast.LENGTH_SHORT).show();
}
}

5直接绑定到标签

activity_main.xml:

添加 android:onClick=“myClick”。如下所示:

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public void myClick(View view) {
Toast.makeText(getApplicationContext(), “你点击了按钮5”, Toast.LENGTH_SHORT).show();
}
}

总结

到此这篇关于android studio按钮监听的5种方法实例详解的文章就介绍到这了,更多相关android studio按钮监听内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。