Android自定义标题栏

来源:互联网 发布:剑三成男大叔脸型数据 编辑:程序博客网 时间:2024/05/21 07:59

原链接:http://dev.10086.cn/cmdn/wiki/index.php?edition-view-6999-1.html

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

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

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

XML/HTML代码
  1. view plaincopy to clipboardprint?  
  2. <style name="CustomWindowTitleBackground">     
  3.     <item name="android:background">@drawable/title_bg</item>    
  4. </style>     
  5.     
  6. <style name="test" parent="android:Theme" mce_bogus="1">     
  7.     <item name="android:windowTitleSize">40dp</item>     
  8.     <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>    
  9. </style>    


然后修改AndroidMainfest.xml文件:

XML/HTML代码
  1. view plaincopy to clipboardprint?  
  2. <activity android:name=".MainActivity"     
  3.           android:theme="@style/test">     
  4.     <intent-filter>     
  5.          <action android:name="android.intent.action.MAIN" />     
  6.          <category android:name="android.intent.category.LAUNCHER" />     
  7.     </intent-filter>     
  8. </activity>    

红色部分为加载Activity的theme。

接着修改MainActivity:

XML/HTML代码
  1. view plaincopy to clipboardprint?  
  2. public void onCreate(Bundle savedInstanceState) {     
  3.      super.onCreate(savedInstanceState);     
  4.      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //声明使用自定义标题     
  5.      setContentView(R.layout.main);     
  6.      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);//自定义布局赋值     
  7. }    

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

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

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

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

原创粉丝点击