Android Floating Action Button, Snackbar, List View Example

This example will tell you how to open a popup alert dialog when user click a floating action button, and after user input user name in the dialog, it will save the user name in the list view in the main screen. If the user name exist, it will popup a message use android snackbar.

1. Example Project Files.

Android studio provide basic activity template for you to generate and include floating action button and snackbar ui components in your app easily, so when you create the project just select basic activity template.

select basic activity template when create new android project

Basic activity template will generate below source files automatically.

basic activity template created source files

Basic activity auto created source files.

  1. MainActivity.java
  2. activity_main.xml
  3. content_main.xml

Popup dialog layout xml file is created by hand.

  1. input_user_name.xml

2. Main Activity Java File.

MainActivity.java

package com.dev2qa.floatingbutton;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // This is the list view object placed in content_main.xml file.
    private ListView userNameListView = null;

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

        setTitle("dev2qa.com - Android Floating Action Button, Snackbar, List View Example");

        userNameListView = findViewById(R.id.list_view_user_name);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupDialog();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showPopupDialog()
    {
        // Create a AlertDialog Builder.
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
        // Set title, icon, can not cancel properties.
        alertDialogBuilder.setTitle("Add User Name.");
        alertDialogBuilder.setIcon(R.drawable.add_icon_56);
        alertDialogBuilder.setCancelable(false);

        LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
        final View inputUserNameView = layoutInflater.inflate(R.layout.input_user_name, null);

        alertDialogBuilder.setView(inputUserNameView);

        final AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        Button saveUserNameButton = inputUserNameView.findViewById(R.id.button_save_username);
        saveUserNameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText editText = inputUserNameView.findViewById(R.id.edit_text_username);

                String userName = editText.getText().toString();

                if(TextUtils.isEmpty(userName))
                {
                    // If user name is empty then popup a snackbar.
                    Snackbar.make(v, "User name can not be empty.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                }else
                {
                    // Create a new string list to store listview item string.
                    List<String> userNameList = new ArrayList<String>();

                    // Indicate whether newly added name exist in current list view or not.
                    boolean addedNameExist = false;

                    // Add all current list view item string to string list.
                    if(userNameListView != null) {
                        ListAdapter listAdapter = userNameListView.getAdapter();

                        if(listAdapter != null) {
                            int itemCount = listAdapter.getCount();
                            for (int i = 0; i < itemCount; i++) {
                                Object item = listAdapter.getItem(i);
                                if (item != null) {
                                    if (item instanceof String) {

                                        String itemString = (String) item;
                                        if (itemString.equalsIgnoreCase(userName)) {
                                            addedNameExist = true;
                                        }

                                        userNameList.add(((String) item));
                                    }
                                }
                            }
                        }
                    }

                    // If newly added user name do not exist in current list view.
                    if(!addedNameExist)
                    {
                        userNameList.add(userName);

                        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, userNameList);
                        userNameListView.setAdapter(arrayAdapter);

                        userNameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
                                Object clickItemObj = adapterView.getAdapter().getItem(index);
                                Toast.makeText(getApplicationContext(), "You clicked " + clickItemObj.toString(), Toast.LENGTH_LONG).show();
                            }
                        });

                        alertDialog.hide();
                    }else
                    {
                        Snackbar.make(v, "User name exist, please input another one.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    }
                }
            }
        });


        Button cancelUserNameButton = inputUserNameView.findViewById(R.id.button_cancel_username);
        cancelUserNameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });

    }
}

3. Main Activity Layout Xml File.

app / res / layout / activity_main.xml

Please note.

  1. CoordinatorLayout make floating action button move up when snackbar popup at the screen bottom.
  2. android:scaleType=”center” make the floating button icon display correctly.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    tools:context="com.dev2qa.floatingbutton.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

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

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:scaleType="center"
        android:backgroundTint="@android:color/white"
        app:srcCompat="@drawable/add_icon_56" />

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

4. Content Layout Xml File.

app / res / layout / content_main.xml

This layout xml file is included by the activity_main.xml file. You can place activity main ui components in this file. There is just a listview in this example.

<ListView
    android:id="@+id/list_view_user_name"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

5. Popup Dialog Layout Xml File.

app / res / layout / input_user_name.xml

This layout xml file is used for the popup dialog when user click the floating action button. It just display an input text box for user to input user name with save and cancel button.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edit_text_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input user name." />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_save_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Save"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/button_cancel_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Cancel"
            android:textAllCaps="false"/>

    </LinearLayout>
</LinearLayout>
READ :   Android Fragment Communication With Activity Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.