问题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>