Android Toolbar绑定及Fab点击事件示例
这段代码绑定的是'app_bar_main.xml'布局文件中的'toolbar'控件。
setSupportActionBar(binding.appBarMain.toolbar);
binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, 'Replace with your own action', Snackbar.LENGTH_LONG)
.setAction('Action', null).show();
}
});
代码解释:
setSupportActionBar(binding.appBarMain.toolbar):将布局文件中的'toolbar'控件设置为Activity的Toolbar,以便使用Toolbar的功能,如标题显示、菜单等。binding.appBarMain.fab.setOnClickListener(...):为'fab'控件添加点击事件监听器。Snackbar.make(view, 'Replace with your own action', Snackbar.LENGTH_LONG):创建Snackbar提示,显示在屏幕底部,内容为'Replace with your own action',持续时间为长提示。.setAction('Action', null).show():添加一个按钮,文本为'Action',点击按钮后不会执行任何操作('null'),并显示Snackbar。
注意:
- 确保在布局文件'app_bar_main.xml'中定义了'toolbar'和'fab'控件。
- 需要在项目的'build.gradle'文件中添加依赖:
implementation 'com.google.android.material:material:1.7.0'(或其他版本)。
原文地址: https://www.cveoy.top/t/topic/i0uc 著作权归作者所有。请勿转载和采集!