在安卓中不喜欢系统默认的标题栏,那么如何让自定义一个自己的标题栏呢。
自定义后的标题栏如下:
首先这里需要定义一个自定义的标题栏布局 title.xml文件 (里边需要两个图片这个很简单)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp" <!-- 新的 标题栏的 高度-->
android:background="#f2f8f8">
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="20dp"
android:src="@drawable/lbt" />
<TextView
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="自定义标题栏"
android:textSize="20sp"
android:gravity="center_vertical"
/>
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:src="@drawable/rbt" />
</RelativeLayout>
然后再MainActivity中声明使用自定义的标题栏
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//声明使用自定义的标题栏
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
//使用自定义的标题栏
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
}
}
接下来我们再来设置标题栏的高度 以及 处理两侧没有完全覆盖原始标题栏的bug,这时 我们需要在定义一个style文件 MyStyle.xml
在自定义标题栏中经常回遇到没有填充完全的效果如下图:
MyStyle.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="titleBarStyle" parent="android:Theme">
<item name="android:windowTitleSize">50dp</item><!-- 原始标题栏的高度 -->
<item name="android:padding">0dp</item><!-- 使新的标题栏完全延伸到对齐到原始标题栏的两边 -->
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mytitle"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.mytitle.MainActivity"
android:label="@string/app_name"
android:theme="@style/titleBarStyle">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
到这里基本就修改完成了。
源码下载地址:http://download.csdn.net/detail/liuhenghui5201/7644123