您的位置:首页 > 其它

安卓学习随笔 -- 自定义标题栏

2014-07-16 21:39 423 查看
在安卓中不喜欢系统默认的标题栏,那么如何让自定义一个自己的标题栏呢。

自定义后的标题栏如下:



首先这里需要定义一个自定义的标题栏布局 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>


然后呢 在 AndroidManifest.xml 中给activity 添加 一个theme属性
<?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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: