Android Floating Action Button- Simple Example
1. The Project Download Link
The entire project can be downloaded from this github repo.
2. Adding Dependencies
We just need to add the following sentence to build.gradle
. This allows you to add supporting material design components and patterns to your apps.
compile 'com.android.support:design:24.2.1'
3. Adding Floating Action Button
Next, we need to add floating action button to activity_main.xml
.
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@android:drawable/ic_menu_send" />
The complete activity_main.xml will be like this after adding the above code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.example.aknay.floatingactionbutton.MainActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@android:drawable/ic_menu_send" />
</android.support.design.widget.CoordinatorLayout>
4. Adding click action for Floating Action Button
Finally, all we just need to add is set on click listener for the floating action button in MainActivity
. We want to see action when click on it, don’t we?
FloatingActionButton mFloatActionButton = (FloatingActionButton) findViewById(R.id.fab_button);
mFloatActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Sending dummy email", Toast.LENGTH_SHORT).show();
}
});
The complete code for ‘MainActivity.java’ will be like the following code.
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton mFloatActionButton = (FloatingActionButton) findViewById(R.id.fab_button);
mFloatActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Sending dummy email", Toast.LENGTH_SHORT).show();
}
});
}
}
5. Run the Application
You will see this view after the application is successfully run.