[Android] Display Snackbar from any position

Overview

Display Snackbar from any position instead of pulling it out from the bottom of the screen

Put Coordinator Layout in the layout file

fragment_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginTop="200dp"
            android:gravity="center" />

     </androidx.coordinatorlayout.widget.CoordinatorLayout>

</LinearLayout>

Wrap the View you want to display the Snackbar with the Coordinator Layout

Snackbar implementation

build.gradle


dependencies {
    implementation 'com.google.android.material:material:1.1.0'
}

ʻImplementation`` com.google.android.materialtobuild.gradle to use Snackbar`

MainFragment.java



import com.google.android.material.snackbar.Snackbar;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    Button button = view.findViewById(R.id.button);
    button.setText("button");
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showSnackbar("test");
        }
    });
    super.onViewCreated(view, savedInstanceState);
}

private void showSnackbar(String message) {
    View view = getView();
    if (view == null) return;

    Snackbar snackbar = Snackbar.make(view.findViewById(R.id.button), message, Snackbar.LENGTH_SHORT);
    snackbar.show();
}

Create a method for displaying Snackbar Set the first argument of Snackbar.make to the id of the View at the position you want to display (this time Button) Make Snackbar come out from under the button's View when the button is pressed

There are a lot of extra descriptions, and I think there is a better way, but it's a memorandum, so I wonder if this is all right. ..

Recommended Posts

[Android] Display Snackbar from any position
[Android] Review dialog display
Android app to select and display images from the gallery
JSP error display from Servlet