使用setCustomView建立标题居中的自定义ActionBar
ActionBar因为溢出菜单的原因导致没有办法让标题居中,但是我们又经常有样式需要标题居中,所以使用自定义ActionBar的布局是最正确的选择,可以在xml布局文件中进行视图的定制。
定制使用到的api是ActionBar中提供的 void setCustomView(View) 函数。
定义的视图是这个样子的:
标题终于居中了。
这里没有涉及到任何ActionBar的style修改,也只有一个activity;
MainActivity.java
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 返回箭头(默认不显示)
- getActionBar().setDisplayHomeAsUpEnabled(false);
- // 左侧图标点击事件使能
- getActionBar().setHomeButtonEnabled(true);
- // 使左上角图标(系统)是否显示
- getActionBar().setDisplayShowHomeEnabled(false);
- // 显示标题
- getActionBar().setDisplayShowTitleEnabled(false);
- //显示自定义视图
- getActionBar().setDisplayShowCustomEnabled(true);
- View actionbarLayout = LayoutInflater.from(this).inflate(
- R.layout.actionbar_layout, null);
- getActionBar().setCustomView(actionbarLayout);
- }
- }
actionbar_layout.xml
- <?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:gravity="center_vertical"
- android:paddingLeft="10dp"
- android:paddingRight="10dp" >
- <ImageButton
- android:id="@+id/left_imbt"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_centerVertical="true"
- android:background="@null"
- android:src="@drawable/b" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:textColor="#FFFFFFFF"
- android:textSize="18sp"
- android:text="标题" />
- <!-- actionbar 右边按钮 -->
- <ImageButton
- android:id="@+id/right_imbt"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_centerVertical="true"
- android:background="@null"
- android:src="@drawable/k" />
- </RelativeLayout>
b.png:;k.png
虽然只有这两个文件用到和修改到,但是最小的版本也要支持ActionBar;
这里补充一下setHomeButtonEnabled函数,控制左上角图标是否显示出来,小于4.0版本的默认值为true的。在4.0及其以上默认值是false;
本文来自****博客 转载请联系作者
并注明出处http://blog.****.net/dreamintheworld/article/details/39314121