要先获取当前视图的 ActionBar ,通过 getSupportActionBar()获取。然后屏蔽系统默认的标题和显示自定义的标题,通过 setDisplayShowTitleEnabled(false) 和 setDisplayShowCustomEnabled(true)进行设置。代码如下
private void setActionBar(){
if (getSupportActionBar() != null){
getSupportActionBar().setElevation(0); //去掉阴影
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
View view = getLayoutInflater().inflate(R.layout.acitonbar, null, false);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.HORIZONTAL_GRAVITY_MASK | Gravity.CENTER_HORIZONTAL;
getSupportActionBar().setCustomView(view, layoutParams);
}
}
xml布局, 名字为 acitonbar :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/shoppingcat_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="购物车(0)"
android:textColor="@android:color/white"
android:textSize="20sp" />
<Button
android:id="@+id/actionBar_edit"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@android:color/transparent"
android:text="编辑"
android:textColor="@android:color/white"
android:textSize="18sp" />
</RelativeLayout>
网友评论