Android Snackbar Tutorial With Material Design

 In previous posts we have seen toast to display a message, alert box or dialog box to display a message the message may be output or may be sometimes system error depending upon requirement but now we have similar display system called as Snackbar.

Android Snackbar :

Snackbar displays a piece of message at the bottom of the screen which appears much more stylish than the normal toast so we will see it in the present tutorial.

This Snackbar is made available with latest api supporting design.This is a material design  available for providing high end design. 

Add support:design which is required for CoordinatorLayout whic is used to display a Snackbar in android add it to your gradle file as

 Dependency’s

Try to check for the latest version of dependency’s before implementing

    compile 'com.android.support:design:23.0.1'

snackbar.xml : 

Adding a CoordinatorLayout to the activity file and also a button. This CoordinatorLayout  helps in displaying a message and also a action button which will perform a desired action on user click.

CoordinatorLayout :

<android.support.design.widget.CoordinatorLayout
        android:id="@+id/CoordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.design.widget.CoordinatorLayout>
<LinearLayout
    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:orientation="vertical"
    tools:context=".SnackBarActivity">


    <Button
        android:id="@+id/SnackBarbut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show SnackBar" />

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/CoordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.design.widget.CoordinatorLayout>

</LinearLayout>

 

SnackBarActivity.java :

Firstly initialize snackbarCoordinatorLayout

snackbarCoordinatorLayout = (CoordinatorLayout)findViewById(R.id.CoordinatorLayout);

And now initialize button and also set on click listener

        btnShowSnackBar = (Button)findViewById(R.id.SnackBarbut);
        btnShowSnackBar.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Snackbar snackbar = Snackbar.make(snackbarCoordinatorLayout, "AndroidCoding.in",
                        Snackbar.LENGTH_LONG);

                snackbar.setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(SnackBarActivity.this, "Android Coding", Toast.LENGTH_LONG).show();
                    }
                });

 

As you can notice we have also given time duration as Long for the snack bar from below line. 

Snackbar snackbar = Snackbar.make(snackbarCoordinatorLayout, "Snackbar",
                        Snackbar.LENGTH_LONG);

 

And now we can set the Action for the Snackbar this is the main feature as i consider because in toast there is no button for user to accept it or perform any action but in Snackbar it is accepting a action by which you can get a piece of work done a s you can move from activity to another or sny thing which you want it be done when you click on that action button and the coding for it goes on like this

snackbar.setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(SnackBarActivity.this,"snackbar OK clicked", 
                           Toast.LENGTH_LONG).show();
                    }
                });

At last don’t forget to add this line as this plays a crucial role in showing a Snackbar on user screen i.e., show functionality and its not anything new you have seen it for Toast, AlertBox and  a few more….

  snackbar.show();

 

package com.androidcoding.snackbar;

import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SnackBarActivity extends AppCompatActivity {

    Button btnShowSnackBar;
    CoordinatorLayout snackbarCoordinatorLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.snackbar);

        snackbarCoordinatorLayout = (CoordinatorLayout)findViewById(R.id.CoordinatorLayout);

        btnShowSnackBar = (Button)findViewById(R.id.SnackBarbut);
        btnShowSnackBar.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Snackbar snackbar = Snackbar.make(snackbarCoordinatorLayout, "Snackbar",
                        Snackbar.LENGTH_LONG);

                snackbar.setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(
                                SnackBarActivity.this,
                                "snackbar OK clicked",
                                Toast.LENGTH_LONG).show();
                    }
                });

                snackbar.show();
            }

        });
    }

}

Output :

The screen depicts Android Snackbar

Android Tutorial on Vibration | How to vibrate device on button click

 Introduction :

Android has got a lot of features which all of us know and in every tutorial i am using one of it to make our app and this time i have brought a new tutorial topic vibration which you might have experienced a lot of times.

People use this feature to avoid loud sound or music when we receive a phone call or a message or any other device broadcast we may use silent but we will not get notified.

Vibration mode is useful in these kinds of situations by alerting user regarding the incoming call or any other services like notifications, messages…

Yes, you are right vibration is not only a feature of android but you can also find it in many basic devices.Here, we are going to see how to implement it in android. 

Android Tutorial on Vibration :

Generally vibration mode is used to notify user regarding any message, phone call, when we deactivate sounds i.e., ringtones and also for any other notifications which may include alert / error messages.

So here i think i now you got a basic knowledge regarding vibration mode, or uses of vibration, so we can move forward.

Note :  Android vibration tutorial is updated because of the latest android changes in the new versions starting from Api 26 and i have provided the code below after the previous code do go through it and let me know in comment section if any help required.


Creating activity_vibrate.xml :

 

Its a simple interface where just we require a button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">


    <Button
        android:id="@+id/vibrate"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_marginTop="50dp"
        android:background="@drawable/vibrate" />


</LinearLayout>

 

Creating a VibrateActivity.java :

Here we will be using vibrator service which is a part of system services in android.

Vibrator = (Vibrator)getSystemService(MainActivity.VIBRATOR_SERVICE);

 

package vibrator.androidcoding.abhishek.vibrator;

import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;

import vibrator.androidcoding.abhishek.vibrator.R;

public class MainActivity extends Activity {

    Button buttonVibrate;

    Vibrator Vibrator;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonVibrate = (Button)findViewById(R.id.vibrate);


        /*Vibrator = (Vibrator)getSystemService(MainActivity.VIBRATOR_SERVICE);*/

        buttonVibrate.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                /*Vibrator.vibrate(1000);*/
                 vibrate();

            }});

    }

// new code update which latest devices supports old and new devices
private void vibrate() {

if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(1000,10));
    } else {
        ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(1000);
    }
    
}
}

 

AndroidManifest.xml :

We need to add a permission for vibration and this is the crucial step as without permission your app may not be able to make device vibrate. 

<uses-permission android:name="android.permission.VIBRATE" />

 

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="vibrator.androidcoding.abhishek.vibrator" >

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

Output :

This screen depicts the Android Tutorial on Vibration

 

Solve the problem of Android Q(10) open failed: EACCES (Permission denied)

 1. Add in Manifest.xml

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 1
  • 2

2. Dynamic permission acquisition

private void requestPermission(){

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ //When not authorized
        //Make authorization
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
    }else{
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //Agree to the permission application
            }else { //Reject permission request
                Toast.makeText(this,"Permission denied",Toast.LENGTH_SHORT).show();
            }
            break;
        default:
            break;
    }
}

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermission();
        .
        .
        .
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

3. Android 10 Google added a new restriction

Related instructions:
Scoped Storage
Q: How can the application temporarily exempt Q’s external storage sandbox restriction?

A: No. Therefore, we strongly recommend that the application adapt in the Q version, but if you need more time, you can consider adding application android:requestLegacyExternalStorage = “true” to the Manifest. If you want to check whether the exemption is exempt, use the Environment.isExternalStorageLegacy() function.

<application
			.
			.
			.
			
        android:requestLegacyExternalStorage="true"
        	.
        	.
        	.
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...