Android自定义标题栏

来源:互联网 发布:收购淘宝店铺多少钱 编辑:程序博客网 时间:2024/06/01 15:22

Android程序中默认标题栏是灰色背景,内容是工程名字,类似下图:

修改了标题栏布局,效果如下:

说一下具体步骤。首先,修改标题栏的宽度和背景,在strings.xml中添加:

[xhtml] view plain copy print?
  1. <style name="CustomWindowTitleBackground">   
  2.     <item name="android:background">@drawable/title_bg</item>  
  3. </style>   
  4.   
  5. <style name="test" parent="android:Theme" mce_bogus="1">   
  6.     <item name="android:windowTitleSize">40dp</item>   
  7.     <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>  
  8. </style>  

然后修改AndroidMainfest.xml文件:

[xhtml] view plain copy print?
  1. <activity android:name=".MainActivity"   
  2.           android:theme="@style/test">   
  3.     <intent-filter>   
  4.          <action android:name="android.intent.action.MAIN" />   
  5.          <category android:name="android.intent.category.LAUNCHER" />   
  6.     </intent-filter>   
  7. </activity>  

红色部分为加载Activity的theme。

接着修改MainActivity:

[java] view plain copy print?
  1. public void onCreate(Bundle savedInstanceState) {   
  2.      super.onCreate(savedInstanceState);   
  3.      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //声明使用自定义标题   
  4.      setContentView(R.layout.main);   
  5.      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);//自定义布局赋值   
  6. }  

注意红色部分标记的3行代码,顺序不能颠倒。

最后在layout文件夹中添加title.xml文件,内容如下:

[xhtml] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:orientation="horizontal"  
  4.     android:layout_width="fill_parent"   
  5.     android:layout_height="fill_parent">   
  6.   
  7.     <ImageView android:layout_width="wrap_content"   
  8.         android:layout_centerVertical=’true’   
  9.          android:layout_height="wrap_content"   
  10.         android:src="@drawable/ic_launcher_email" />   
  11.     <TextView android:layout_width="wrap_content"   
  12.         android:layout_centerInParent="true"   
  13.         android:layout_height="wrap_content"   
  14.         android:text="自定义标题栏" />   
  15.   
  16. </RelativeLayout>  

重新部署程序,效果如上图。

源码连接:http://bigcateasymorse.googlecode.com/svn/trunk/androidcustomtitle/

0 0
原创粉丝点击