Snackbar is a Simple Message in Display Same as a Toast But it Advance And Change User Display Message in Snackbar.It Can Handle Custom Click Event of Snackbar and Perform Action in Button.Change Background And TextColor And Action button color to change and customization.Snackbar is a display of style.and better than toast message to display in snackbar.
Add Dependancy In App Module build.gradle file
implementation 'com.android.support:design:27.1.1'
MianActivity.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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/btn_default" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Default Snackback" android:layout_marginTop="20dp" android:textAllCaps="false" android:layout_gravity="center_horizontal" /> <Button android:id="@+id/btn_custom" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Custom Snackback" android:textAllCaps="false" android:layout_gravity="center_horizontal" /> </LinearLayout>
MainActivity.java
package com.example.com.snackbardemo; 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.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button btn_default,btn_custom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_default = findViewById(R.id.btn_default); btn_custom = findViewById(R.id.btn_custom); btn_default.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Snackbar.make(btn_default,"This is Default Snackbar",Snackbar.LENGTH_LONG).show(); } }); btn_custom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Snackbar snackbar = Snackbar.make(btn_custom,"This is Custom Snackbar",Snackbar.LENGTH_LONG) .setAction("Close", new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Close Button Click", Toast.LENGTH_SHORT).show(); } }) .setActionTextColor(Color.GREEN); TextView textView = snackbar.getView().findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.RED); snackbar.show(); } }); } }
0 comments:
Post a Comment