Android 自定义标题栏

最近在做android应用的时候,感觉系统自带的标题栏不是很美观,所以就想这能自定义标题栏,在网上找的了很多方法,但是都不是很完美,今天就记录下如何自定义标题栏。

一:创建Android应用

    首先在eclipse里面创建一个android应用:DiyTitle

二:编写布局文件

   因为要采用自定义标题,所以这里需要创建一个布局文件来作为标题栏的布局,这里我就简单的使用一个文字信息作为标题,布局如下:

<?xml version="1.0" encoding="utf-8"?>     
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     
    android:orientation="horizontal"  
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent">
    
  

    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/app_name" 
        android:textSize="23sp"/>

  
          
</RelativeLayout>

  这里需要设置android:layout_centerInParent="true",才能让文字居中显示,接下来就要修改主题,在style.xml中添加自定义的样式:

     <style name="mywindowTitleBackground">
       
         <item name="android:background">@color/titleBgColor</item>	
    </style>

  在values目录下创建一个theme.xml文件,定义标题相关属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="themeTitle" parent="android:Theme.Light">
		<item name="android:windowTitleSize">46dip</item>
		<item name="android:windowTitleBackgroundStyle">@+style/mywindowTitleBackground</item>
		<item name="android:windowBackground">@color/windowbackgroud</item>
		<item name="android:textColor">@color/black</item>
	</style>
</resources>

  同时创建颜色配置文件drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="windowbackgroud">#44BBBF</color>
   <color name="black">#000000</color>
   <color name="white">#fff</color>
   <color name="gray">#808080</color>
   <color name="titleBgColor">#1AA6B5</color>
   <color name="titleTextColor">#fff</color>
   <color name="singNameColor">#10808E</color>
   <color name="btnClick">#EEE5DE</color>
   <color name="listViewDivider">#30A1A5</color>
</resources>

   该文件定义了一些颜色,可以自定义修改

然后将AndroidManifest.xml中指定的主题修改为我们上面定义的

 <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/themeTitle" >

     设置为themeTitle,这样就差不多了

三: 编写代码

  在MainActivity中设置标题栏的样式,注意顺序:

package com.jacksoft.diytitle;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Window;

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

四:运行

   这样就可以了,运行吧,结果如下:



 

猜你喜欢

转载自mybar.iteye.com/blog/1985910