Android自定义标题栏

1.首先在onCreate方法里定义

@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);

}

2.在res/layout里新建title.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:id="@+id/gallery_title_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="××××"
        android:textColor="#ffffff"
        android:textStyle="bold" 
        android:textSize="20dp"/>
    
</LinearLayout>

3.再在res/values里新建style.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
   <style name="CustomWindowTitleBackground"> 
      <item name="android:background">@drawable/bg</item>      <!--bg为标题的背景图片.9.png格式-->
   </style> 
   <style name="CustomTitleBar" parent="android:Theme"> 
      <item name="android:windowTitleSize">45dp</item> 
      <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>     <!--设置titlebar的背景-->
   </style> 
</resources>

4.最后在androidManifest.xmlwenj

<activity 
     android:name="com.xyscience.lr.mainUI.GalleryDetails" 
     android:theme="@style/CustomTitleBar" >
</activity> 


OK,大功告成!

你可能感兴趣的:(Android自定义标题栏)