Search code examples
javaandroidandroid-activitylayoutfragment

Implement a button which is reachable from every fragment and activity


Is there a way to implement a button that can be reached from everywhere? The Button should visible in every view of the app.


Solution

  • You can't make a button that exists in every activity & fragment, but you can make a button for each activity and they all look the same in each activity. I prefer using a FloatingActionButton, and here is how to use it :

    First implement androidx.appcompat:appcompat:1.1.0 to your gradle file :

    implementation 'androidx.appcompat:appcompat:1.1.0'
    

    Then add this code to the XML file for each activity just like any other view ( but add it as the last view ):

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:layout_gravity="right|bottom"
        app:srcCompat="@drawable/an_icon_for_the_button"/>
    

    Then import these to each activity:

    import androidx.appcompat.app.AppCompatActivity;
    import androidx.annotation.*;
    import com.google.android.material.floatingactionbutton.FloatingActionButton
    

    Then add the FloatingActionButton to each activity:

    private FloatingActionButton _fab;
    

    The add this to the onCreate void in each activity:

    _fab = (FloatingActionButton) findViewById(R.id._fab);
    _fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View _view) {
                //here enter what will happen when the user clicks the button
                //in your example, this will open the sidebar
            }
        });