首先上完整代码:
oncreate中:
boolean isCustom = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);// 注意这里一定要在setContentView之后setFeatureInt,在PreferenceActivity中需要在onCreate之后即可因为其中已经实现了setContentView()方法
if (isCustom) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.actionbar_default);
}
((TextView) findViewById(R.id.action_bar_title))
.setText(R.string.title);
findViewById(R.id.back).setOnClickListener(new OnClickListener() {
@Overridepublic
void onClick(View v) {
finish();
}
});
布局文件layout:
actionbar_default.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:layout_centerVertical="true"
android:background="@color/app_color"
android:orientation="horizontal" >
<ImageView
android:id="@+id/back"
style="@style/NormalButtonLeftStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="@drawable/btn_back" />
<TextView
android:id="@+id/action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/back"
android:textColor="@android:color/white"
android:textSize="16sp" />
</RelativeLayout>
然后添加style:
<style name="CustomWindowTitleBackground">
<item name="android:background">@color/actionbar_bg</item>
</style>
<style name="preferenceStyle" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
<item name="android:windowNoTitle">false</item>
<item name="android:windowTitleSize">52dp</item>
</style>
然后在AndroiManifest.xml设置:
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:theme="@style/preferenceStyle" >
</activity>
其中部分资源以及名称根据自己具体情况修改。