[英]Show a snackbar to a menu click event in Android
I have a menu on android and want to show a simple snackbar anywhere after there was a click on a menu item. 我在Android上有一个菜单,想在点击一个菜单项后随时随地显示一个简单的小吃吧。 Whatever I put something else instead of "???"
无论我把别的什么东西放在“???” doesn't work.
不起作用。 The whole app is from the Android studio default tab view template.
整个应用程序来自Android studio默认选项卡视图模板。 This is the code I have:
这是我的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Snackbar.make("????", "Pressed Setting", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
if (id == R.id.help_settings) {
Snackbar.make("???", "Pressed Help", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
return super.onOptionsItemSelected(item);
}
Why is it behaving like that? 为什么它表现得那样? And how can I fix it?
我该如何解决?
Change 更改
Snackbar.make("???", ....)
to 至
Snackbar.make(getWindow().getDecorView(), .....);
You must pass in a View
to the Snackbar
's static make
method. 您必须将
View
传递给Snackbar
的静态 make
方法。
This is how you show Snackbar
on menu item click: 这是您在菜单项单击上显示
Snackbar
:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Snackbar.make(this.findViewById(R.id.action_settings), "Pressed Setting", Snackbar.LENGTH_LONG).show();
}
if (id == R.id.help_settings) {
Snackbar.make(this.findViewById(R.id.help_settings), "Pressed Help", Snackbar.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
I tried this, it worked with me 我试过这个,它和我一起工作
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
Snackbar.make(getCurrentFocus(), "U Clicked Settings",Snackbar.LENGTH_LONG).setAction("Action", null).show();
return true;
}
}
这对我有用,我错过了.show()
Snackbar.make(getCurrentFocus(),"settings clicked",Snackbar.LENGTH_LONG).show();
tried this, it worked fine 试过这个,它工作得很好
Snackbar.make(findViewById(android.R.id.content),
"Pressed Settings", Snackbar.LENGTH_LONG).show()
getCurrentFocus()
, findViewById()
and getWindow()
won't work directly. getCurrentFocus()
, findViewById()
和getWindow()
将无法直接工作。
To use those functions, first get the instance of Activity and then cast it to your activity (The one that contains the current fragment). 要使用这些函数,首先获取Activity的实例,然后将其转换为您的活动(包含当前片段的活动)。 For example:
例如:
Snackbar.make((activity as YourActivity).findViewById(R.id.action_settings),
"Pressed Settings", Snackbar.LENGTH_LONG).show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.