【问题标题】:Implement a button which is reachable from every fragment and activity实现一个可以从每个片段和活动中访问的按钮
【发布时间】:2021-12-16 21:06:38
【问题描述】:

有没有办法实现一个可以从任何地方访问的按钮? Button 应该在应用的每个视图中都可见。

【问题讨论】:

    标签: java android android-activity layout fragment


    【解决方案1】:

    您不能制作一个存在于每个活动和片段中的按钮,但您可以为每个活动制作一个按钮,并且它们在每个活动中看起来都一样。 我更喜欢使用 FloatingActionButton,这里是如何使用它:

    首先在你的 gradle 文件中实现 androidx.appcompat:appcompat:1.1.0

    implementation 'androidx.appcompat:appcompat:1.1.0'
    

    然后将此代码添加到每个活动的 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"/>
    

    然后将这些导入到每个活动中:

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

    然后将 FloatingActionButton 添加到每个活动中:

    private FloatingActionButton _fab;
    

    将这个添加到每个活动中的 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
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多