I have a menu on android and want to show a simple snackbar anywhere after there was a click on a menu item. Whatever I put something else instead of "???" doesn't work. The whole app is from the Android studio default tab view template. 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?
To show an Android Snackbar message from an Activity or Fragment, use Java code like this: Snackbar. make(view, "going to: " + url, Snackbar. LENGTH_LONG).
The snackbar should appear when the user presses the button. Text(text = "Click me!") Let's create a default ScaffoldState inside “remember” method to ensure that we use the same state even after re-composition. As I mentioned earlier, the ScaffoldState contains SnackbarHostState that we can use to show a new Snackbar.
This example demonstrates how to use Snackbar in Android Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Combined solution from the above ones: final ViewGroup. LayoutParams params = snackbar. getView().
Change
Snackbar.make("???", ....)
to
Snackbar.make(getWindow().getDecorView(), .....);
You must pass in a View
to the Snackbar
's static make
method.
On some devices the snackbar can appear below the system's controls menu, and for that reason you may wanna call findViewById(android.R.id.content)
to display the snackbar correctly:
Snackbar.make(getWindow().getDecorView().findViewById(android.R.id.content), .....);
This is how you show Snackbar
on menu item click:
@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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With