简体   繁体   中英

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. If I click on it, it should open something like a little Sidebar with information that comes from a database.

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
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM