Skip to content

Instantly share code, notes, and snippets.

@benhaxe
Created December 17, 2017 20:00
Show Gist options
  • Save benhaxe/8418d93f35cdebcf85a6696feb563d7f to your computer and use it in GitHub Desktop.
Save benhaxe/8418d93f35cdebcf85a6696feb563d7f to your computer and use it in GitHub Desktop.
Best practice for displaying short information to user in replace of using the Toast
// Advised to set the root tag of your layout to the coordinate layout and give it a id
// So i will just comment the layout file code
/*
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/cl_forSnackBar"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="banhaxe.io.testwork.SnackBar">
</android.support.design.widget.CoordinatorLayout>
*/
/*The java code starts here*/
package banhaxe.io.testwork;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class SnackBar extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snack_bar);
View view = findViewById(R.id.cl_forSnackBar);
String message = "Showing Snack Bar when activity is created";
int duration = Snackbar.LENGTH_INDEFINITE;
showSnackBar(view, message, duration);
}
/*this is a general use case for any snack bar just call the method and pass in your preferred parameters*/
// Create the snack bar
public void showSnackBar(View mView, String mMessage, int mDuration){
final Snackbar snackbar = Snackbar.make(mView, mMessage, mDuration);
// set Action on the snack bar
snackbar.setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View view) {
// This code only remove the snack bar feel free to replace with your own action
snackbar.dismiss();
}
});
// Styling the snack bar
// [Dismiss] color will be white
snackbar.setActionTextColor(Color.MAGENTA);
// The [getView] method is to get the whole view of the snack bar
View snackView = snackbar.getView();
snackView.setBackgroundColor(Color.GRAY);
// Note: the Message of the snack bar is a Text View
// The in built id is [android.support.design.R.id.snackbar_text]
TextView snackBar_Tv = snackView.findViewById(android.support.design.R.id.snackbar_text);
snackBar_Tv.setTextColor(Color.WHITE);
// Show the snack bar.
snackbar.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment