SnackBar (Android)

//Open build.gradle and add design support library dependency. dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.3.0' //Change your version compile 'com.android.support:design:23.3.0' //Change your version } //CoordinatorLayout allows Snackbar to enable some features like swipe-to-dismiss and automatically moving of widgets like FloatingActionButton. //Create a xml file <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/coordinatorLayout" //You need to set an id for layout tools:context=".MainActivity"> </android.support.design.widget.AppBarLayout> <Button android:id="@+id/btnSnackbar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Simple Snackbar" /> </android.support.design.widget.CoordinatorLayout> //Inside onCreate() private CoordinatorLayout coordinatorLayout; private Button btnSnackbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Get layout, button through ID coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); btnSnackbar = (Button) findViewById(R.id.btnSnackbar); //When user interacts with SnackBar btnSimpleSnackbar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar snackbar = Snackbar .make(coordinatorLayout, "Welcome to SnackBar", Snackbar.LENGTH_LONG) //(1) //If you just wanna show text, Stop at (1), If not, keep going..... .setAction("PRESS HERE", new View.OnClickListener() { //(2) @Override public void onClick(View v) { Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "PRESS HERE is selected", Snackbar.LENGTH_LONG); snackbar1.show(); //Show snackBar out } }); //Changing message text color (1) snackbar.setActionTextColor(Color.BLUE); //Changing action button text color (2) View view1 = snackbar.getView(); TextView textView = (TextView) view1.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.RED); snackbar.show(); //Show snackBar out } }); } }
This Snippet shows you how to create and customize SnackBar in Android.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.