Floating Action Button’s are those neat little buttons you see generally in the lower right corner of an app. They perform some sort of positive action like creating something, like an email or a text. We’re going to see how to add a simple Floating Action Button (hereafter referred to as FAB) to an activity.
For an excellent list of design considerations when creating FAB’s, see Google’s page here.
Add the Gradle Dependency
In your “build.gradle (Module: app)” file, add the line
Where the x’s are your apps support library version number. This should be the same as the ‘com.android.support:appcompat-v7:xx.x.x’ number.
Add an Image for Your FAB
Add a vector asset to be used in your button by right clicking on your Drawable folder, and going to New -> Vector Asset.
Before you finish adding the icon you want, (I added the plus symbol, called “ic_add”), change the word black to white. We won’t actually change the color here because we need to create the file first but it’s easier to change the name now than later.
Change the Icon Color
Once you’ve created the icon, it will be added to your Drawable folder. Double click on it to open the file. Change the fillColor from “#FF000000” to “FFFFFFFF”.
Now Code the FAB
Now add the Floating Action Button in your activity_main xml file.
AlignParentEnd and AlignParentRight are in there to support Right-To-Left (RTL) layouts, where the end would actually be the left.
If you add the FAB and get rendering errors, go to the Build menu and click on Clean Project. If this doesn’t fix it and you get an error that says “Exception raised during rendering: Unable to locate mode 0” this is because of a bug in the 25.0.0 library. Update your library and this should go away.
Respond to Clicks
Now in Main Activity, add the reference to the FAB and add the click listener
public class MainActivity extends AppCompatActivity
protected void onCreate(Bundle savedInstanceState)
fab = (FloatingActionButton) findViewById(R.id.FAB);
public void onClick(View view)
Toast.makeText(getApplicationContext(), "I've been clicked", Toast.LENGTH_SHORT).show();
There you have it! A fine looking Floating Action Button!