Open top menu

 How to used SanckBar in Android ?

They automatically fade out after enough time similar to a toast. The SnackBars provide Lightweight feedback about an operation. They show a brief message at the bottom of the screen on mobile and lower left on larger device. You are make custom Material Design SanckBar, and set Background color programmatically.
 
You can also mention a callback intraction method using setAction() method.


snackbar.setAction("OK", new View.OnClickListener() {
    @Override
   
public void onClick(View v) {
      
     //code here…  
    }
});

And you can also mention Snackbar Auto dismiss duration.

snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);

snackbar.setDuration(Snackbar.LENGTH_LONG);

snackbar.setDuration(Snackbar.LENGTH_SHORT);
 
activity_main.xml
……………………………………………………………………………………………………………………………..
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:id="@+id/layout" >

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!" />



</RelativeLayout>


……………………………………………………………………………………………………………………………..



MainActivity.java.

……………………………………………………………………………………………………………………………..

 


public class MainActivity extends AppCompatActivity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        RelativeLayout layout=(RelativeLayout)findViewById(R.id.layout) ;

        final Snackbar snackbar = Snackbar.make(layout, "Welcome to AndroidBeginnerpoint", Snackbar.LENGTH_LONG);

        snackbar.setAction("OK", new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                snackbar.dismiss();

            }

        });



        snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);

        snackbar.show();

    }

}

……………………………………………………………………………………………………………………………..



0 comments