我對編碼非常陌生,所以我可能無法正確表達自己,請耐心等待。如何訪問Android中的工具欄中的按鈕
我有一個在包含工具欄的佈局中膨脹的片段。當我打開片段時,我想添加一個按鈕(不是菜單,只是一個按鈕導航到另一個片段)。 我的問題是我不知道如何實例化我的Fragment
類中的按鈕來添加圖標和onClickListener
。
這裏是我的xml文件: 包含我的片段佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="be.ac.ulg.mobulis.Activities.MainActivity"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/blue"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<Button
android:id="@+id/toolbar_button"
android:layout_width="@dimen/margin"
android:layout_height="@dimen/margin"
android:layout_gravity="right"
android:layout_marginRight="@dimen/innerLargeMargin"
/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</LinearLayout>
在該片段充氣佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="be.ac.ulg.mobulis.Activities.MainActivity"
tools:showIn="@layout/app_bar_main"
android:background="@color/orange">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#f1f1f1">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
design:menu="@menu/bottom_nav_items"
android:background="@color/orange"
android:backgroundTint="@color/white"
design:itemIconTint="@color/white"
design:itemTextColor="@color/white"
design:itemBackground="@drawable/bottom_bar_tint_selector"
/>
</LinearLayout>
所以我想要做的是一樣的東西
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
toolBarButton = (???).findViewById(R.id.toolbar_button)
}
如果你不想菜單,然後在片段中自定義佈局添加到您的工具欄,這樣你可以很容易地添加一個按鈕或改變你的工具欄。 – Umair