简体   繁体   English

实现一个可从每个片段和活动访问的按钮

[英]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 :我更喜欢使用 FloatingActionButton,这里是如何使用它:

First implement androidx.appcompat:appcompat:1.1.0 to your gradle file :首先实现androidx.appcompat:appcompat:1.1.0到你的 gradle 文件:

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 ):然后将此代码添加到每个活动的 XML 文件中,就像任何其他视图一样(但将其添加为最后一个视图):

<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:然后将 FloatingActionButton 添加到每个活动:

private FloatingActionButton _fab;

The add this to the onCreate void in each activity:将此添加到每个活动的 onCreate void 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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