This example will tell you how to open a popup alert dialog when the user clicks a floating action button, and after the user inputs the user name in the dialog, it will save the user name in the list view on the main screen. If the user name exists, it will popup a message using the android SnackBar.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/-KulntzD9Hg
1. Example Project Files.
- Android studio provides a Basic Activity template for you to generate and include floating action buttons and SnackBar UI components in your app easily.
- So when you create the project just select the Basic Activity template in the Android Studio—> Create New Project —> Add an Activity to Mobile wizard dialog.
- Below is the example project files list.
D:\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\FLOATINGBUTTON │ .gitignore │ build.gradle │ gradle.properties │ gradlew │ gradlew.bat │ settings.gradle │ ├─.idea │ gradle.xml │ misc.xml │ modules.xml │ runConfigurations.xml │ ├─app │ │ .gitignore │ │ build.gradle │ │ proguard-rules.pro │ │ │ └─src │ ├─androidTest │ │ └─java │ │ └─com │ │ └─dev2qa │ │ └─floatingbutton │ │ ExampleInstrumentedTest.java │ │ │ ├─main │ │ │ AndroidManifest.xml │ │ │ │ │ ├─java │ │ │ └─com │ │ │ └─dev2qa │ │ │ └─floatingbutton │ │ │ MainActivity.java │ │ │ │ │ └─res │ │ ├─drawable │ │ │ add_icon_56.png │ │ │ ic_launcher_background.xml │ │ │ │ │ ├─drawable-v24 │ │ │ ic_launcher_foreground.xml │ │ │ │ │ ├─layout │ │ │ activity_main.xml │ │ │ content_main.xml │ │ │ input_user_name.xml │ │ │ │ │ ├─menu │ │ │ menu_main.xml │ │ │ │ │ ├─mipmap-anydpi-v26 │ │ │ ic_launcher.xml │ │ │ ic_launcher_round.xml │ │ │ │ │ ├─mipmap-hdpi │ │ │ ic_launcher.png │ │ │ ic_launcher_round.png │ │ │ │ │ ├─mipmap-mdpi │ │ │ ic_launcher.png │ │ │ ic_launcher_round.png │ │ │ │ │ ├─mipmap-xhdpi │ │ │ ic_launcher.png │ │ │ ic_launcher_round.png │ │ │ │ │ ├─mipmap-xxhdpi │ │ │ ic_launcher.png │ │ │ ic_launcher_round.png │ │ │ │ │ ├─mipmap-xxxhdpi │ │ │ ic_launcher.png │ │ │ ic_launcher_round.png │ │ │ │ │ └─values │ │ colors.xml │ │ dimens.xml │ │ strings.xml │ │ styles.xml │ │ │ └─test │ └─java │ └─com │ └─dev2qa │ └─floatingbutton │ ExampleUnitTest.java │ └─gradle └─wrapper gradle-wrapper.jar gradle-wrapper.properties
- The Basic Activity template will generate the below source files automatically.
MainActivity.java activity_main.xml content_main.xml
- The below popup dialog layout XML file is created by hand.
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, the CoordinatorLayout makes the floating action button move up when the SnackBar popup at the screen bottom.
- The attribute android:scaleType=”center” makes 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 the user clicks the floating action button.
- It just displays an input text box for a user to input the user name with the 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>