天天看點

Fragment中使用setSupportActionBar(),以及toolbar标題居中問題

問題1:Fragment中無法直接使用setSupportActionBar()

解決:

将得到的activity強制轉化成AppCompatActivity

val mActivity = activity as AppCompatActivity
        mActivity.setSupportActionBar(toolbar_fragment_more)
        var actionBar : ActionBar? = mActivity.supportActionBar
           

問題2:Toolbar的标題不居中

解決:将actionbar的标題設為空,然後在toolbar裡放一個TextView控件

由于我直接放TextView不能使用layout_gravity這個屬性,所有為了居中隻能再放一個RalativeLayout,才能實作居中

在Activity中這樣寫

if(actionBar != null){
            actionBar.title = ""
        }
           

在放Toolbar的布局中這樣寫

<androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_fragment_more"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:background="@color/colorSkin">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginRight="18dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="更多"
                android:layout_centerInParent="true"/>
        </RelativeLayout>
    </androidx.appcompat.widget.Toolbar>
           

繼續閱讀