![](/img/trans.png)
[英]How to listen click action of the button which is from Activity on fragment?
[英]Implement a button which is reachable from every fragment and activity
有沒有辦法實現一個可以從任何地方到達的按鈕? 按鈕應該在應用程序的每個視圖中都可見。 如果我點擊它,它應該會打開一個類似小側邊欄的東西,其中包含來自數據庫的信息。
你不能制作一個存在於每個活動和片段中的按鈕,但你可以為每個活動制作一個按鈕,它們在每個活動中看起來都一樣。 我更喜歡使用 FloatingActionButton,這里是如何使用它:
首先實現androidx.appcompat:appcompat:1.1.0
到你的 gradle 文件:
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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.