Android Floating Action Button (New Implementation)

Android Floating Action Button (New Implementation)

The previous tutorial about Floating Action Button implementation is now deprecated regarding that now, there is a support library from Android which makes the implementation of FAB more easier. You just have to add to dependencies the Design Library in your gradle file and this way, you can use the Floating Action Button even for older versions of Android.

1. build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.newfloatingactionbutton"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
}

2. dimens.xml

First go to res – values – dimens.xml and add the following dimensions:

<resources>
    <dimen name="fab_button_margin_bottom">16dp</dimen>
    <dimen name="fab_button_margin_right">16dp</dimen>
</resources>

 

Also, you will have to download the “+” icons which will be displayed on fab. You can download them from below:

[ddownload id=”626″ text=”FAB Plus Icons “]

3. activity_main.xml

Now, go to res – activity_main.xml and add the following code in order to add the floating action button.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@android:color/white">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:transcriptMode="alwaysScroll"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/fab_ic_add"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/fab_button_margin_bottom"
        android:layout_marginRight="@dimen/fab_button_margin_right"
        app:elevation="6dp"
        app:pressedTranslationZ="12dp"
        app:borderWidth="0dp"/>

</RelativeLayout>

Note 1: app:borderWidth="0dp" is needed for API > 21 for now, because it seems there is an issue with the current android support library design. The shadow will not be visible for Lollipop versions if this is not set (for older versions of Android it is ok). Note 2: Notice that in order to add the elevation and translation attributes we have to add 

xmlns:app="http://schemas.android.com/apk/res-auto"

to the root layout.

4. MyCustomAdapter.java

Now we have to create the adapter for the list view. In order to to this, we have to create a new java class and name it MyCustomAdapter. Copy the code below:

package com.example.newfloatingactionbutton;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class MyCustomAdapter extends BaseAdapter {
    private ArrayList mListItems;
    private LayoutInflater mLayoutInflater;

    public MyCustomAdapter(Context context, ArrayList arrayList){

        mListItems = arrayList;

        //get the layout inflater
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        //getCount() represents how many items are in the list
        return mListItems.size();
    }

    @Override
    //get the data of an item from a specific position
    //i represents the position of the item in the list
    public Object getItem(int i) {
        return null;
    }

    @Override
    //get the position id of the item from the list
    public long getItemId(int i) {
        return 0;
    }

    @Override

    public View getView(int position, View view, ViewGroup viewGroup) {

        // create a ViewHolder reference
        ViewHolder holder;

        //check to see if the reused view is null or not, if is not null then reuse it
        if (view == null) {
            holder = new ViewHolder();

            view = mLayoutInflater.inflate(R.layout.list_item, null);
            holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);

            // the setTag is used to store the data within this view
            view.setTag(holder);
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)view.getTag();
        }

        //get the string item from the position "position" from array list to put it on the TextView
        String stringItem = mListItems.get(position);
        if (stringItem != null) {
            if (holder.itemName != null) {
                //set the item name on the TextView
                holder.itemName.setText(stringItem);
            }
        }

        //this method must return the view corresponding to the data at the specified position.
        return view;

    }

    /**
     * Static class used to avoid the calling of "findViewById" every time the getView() method is called,
     * because this can impact to your application performance when your list is too big. The class is static so it
     * cache all the things inside once it's created.
     */
    private static class ViewHolder {

        protected TextView itemName;

    }
}

5. MainActivity.java

And the final step is to go to MainActivity class and add the logic for displaying our list with a Floating Action Button on the right bottom of the screen.

package com.example.newfloatingactionbutton;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView myList;

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

        //relate the listView from java to the one created in xml
        myList = (ListView) findViewById(R.id.list);
        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "Row " + position + " clicked", Toast.LENGTH_SHORT).show();
            }
        });

        FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);

        final ArrayList list = new ArrayList<>();

        //for simplicity we will add the same name for 20 times to populate the list view
        for (int i = 0; i < 5; i++) {
            list.add("Item " + i);
        }

        final MyCustomAdapter adapter = new MyCustomAdapter(MainActivity.this, list);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.add("New Item");
                adapter.notifyDataSetChanged();
            }
        });

        //show the ListView on the screen
        // The adapter MyCustomAdapter is responsible for maintaining the data backing this list and for producing
        // a view to represent an item in that data set.
        myList.setAdapter(adapter);

    }
}

And that’s pretty much it. As you can see, is easier to add FAB now 🙂

Floating Action Button Default

How to Change Floating Action Button’s Color?

The default color, as you could see, is green, so if this color doesn’t match your app colors theme, you will have to change it. You can change just the FAB color by changin the colorAccent from your app theme. But for the purpose of this tutorial I will change the app bar also.

1. Go to  res – values – colors.xml (if you don’t have the colors.xml you just have to right click the values folder – select New – Value resource file  and write colors.xml in the window that opens). Now, that the file is created, add the following colors:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--Color primary 500 from palette colors -->
    <color name="primary">#03A9F4</color>
    <!--Color primary dark 700 from palette colors -->
    <color name="primaryDark">#0288D1</color>
</resources>

2. For pre Lollipop versions (older versions), you just have to go res – values – styles.xml  and copy the code below:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/primary</item>
    </style>

</resources>

3. For Lollipop version, we will have to add an extra item for navigation bar color. So, now, we have to create a new values folder for v21. You can create it like this:

– go to res folder and right click on it – select New – Android Resource directory – and from the Resource type drop down select values – select Version qualifier and inside the edit text from the right write 21.

And now, in the values-v21.xml folder, create a styles.xml file (exactly like colors.xml) and add the following code:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="android:navigationBarColor">@color/primary</item>
        <item name="colorAccent">@color/primary</item>
    </style>

</resources>

And this is how our app looks like now, with the Floating Action Button’s color changed (and navigation bar, for Lollipop) 😀

, , , , , , ,
Previous Post
Android ExpandableList Move Item From Group to Another on Click
Next Post
Android Countdown ProgressBar

Related Posts

Menu