Snackbars are fairly common in the Android app. Almost every app uses a snack bar to display some information about what’s going on in the app. You can consider Snackbar as an alternative or the best version of Toasts in Android.
Step 1: Using a normal Snackbar
To use Snackbar in your app, you just have to have the material design dependency in your app. Add Material design dependency to your build.Gradle app-level.
dependencies {
implementation "com.google.android.material:$latest_version"
}
And then you can use the snack bar just like toast. For example:
Snackbar.make(view, "Show some message here", Snackbar.LENGTH_SHORT).show()
Step 2: Working with the MainActivity.xml
Step 3: Creating a custom layout for a snack bar
Under Layout, the folder creates a layout for the snack bar that must be inflated when creating a snack bar under the mainactivity.java file.
import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = findViewById(R.id.coordinatorLayout);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSnackbar();
}
});
}
public void showSnackbar() {
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Marked as Read", Snackbar.LENGTH_INDEFINITE)
.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Undo successful", Snackbar.LENGTH_SHORT);
snackbar1.show();
}
})
.setActionTextColor(Color.RED);
snackbar.show();
}
}