这篇文章主要介绍了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按钮监听内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:android studio按钮监听的5种方法实例详解
基础教程推荐
猜你喜欢
- iOS Crash常规跟踪方法及Bugly集成运用详细介绍 2023-01-18
- iOS开发 全机型适配解决方法 2023-01-14
- IOS获取系统相册中照片的示例代码 2023-01-03
- Android Compose自定义TextField实现自定义的输入框 2023-05-13
- MVVMLight项目Model View结构及全局视图模型注入器 2023-05-07
- iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi 2023-06-18
- Android开发Compose集成高德地图实例 2023-06-15
- Flutter进阶之实现动画效果(三) 2022-10-28
- iOS开发使用XML解析网络数据 2022-11-12
- Android实现短信验证码输入框 2023-04-29