自定义Android标题栏修改TitleBar的布局

Android程序默认的Activity标题栏只能显示一段文字,而且不能改变它的布局、颜色、标题栏的高度等。如果想要在标题栏加上个图标、button、输入框、进度条、修改标题栏颜色等,只能使用自定义的标题栏。自定义标题栏可以通过在onCreate函数中添加以下代码来实现,需要注意的是代码的顺序必须按照下面的样式,否则将无效。

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);(注意顺序)

setContentView(R.layout.mainactivity); //Activity的布局
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar); //标题栏的布局


如布局文件为下面:

R.layout.titlebar

<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "wrap_content" > < TextView android:text = "@string/app_name" android:textColor = "#000" android:paddingRight = "3.0dip" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> < TextView android:text = "@string/battery_text" android:textColor = "#000" android:paddingRight = "3.0dip" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> < TextView android:id = "@+id/battery_text" android:textColor = "#00f" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </ LinearLayout >

虽然上面这样可以在标题栏加入一些控件,但是仍然不能改变标题栏的高度、背景色,要想达到这个目的,只能使用theme(主题)。因此往project里先添加一个style。改变背景色修改android:windowTitleBackgroundStyle的值,改变标题栏高度则修改android:windowTitleSize的值。下面是一个示例:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomWindowTitleBackground">
<item name="android:background">#778899</item>//标题栏的背景色
</style>
<style name="activityTitlebar" parent="android:Theme">
<item name="android:windowTitleSize">32dp</item>//标题栏的高度
<item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
</style>
</resources>

接着再修改AndroidManifest.xml文件,找到要自定义标题栏的Activity,添加上android:theme值,比如:

<activity android:name=".MainActivity" android:theme="@style/activityTitlebar">

android:theme值就是上面那个style.xml文件里定义的一个style的name值。(即上面的activityTitlebar)

按照以上的步骤,修改标题栏布局、高度、背景色的功能就实现了。

更多相关文章

  1. android 程序异常捕捉处理
  2. android 修改AVD的存放位置
  3. 由安装Busybox到Android过程中想到的
  4. Android(安卓)修改spinner 字体颜色 样式的方法
  5. 处女男学Android(二)---Handler预习篇之Android的线程与UI
  6. Android自定义视图四:定制onMeasure强制显示为方形
  7. Android--About Android(欢迎修改、补充)
  8. 2013.12.04 ——— android SlidingMenu之准备
  9. Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]

随机推荐

  1. android 基本的画图方法
  2. rk3288 android 5.1 EC20 4G module调试
  3. Android(安卓)Activity接收Service发送的
  4. Android本地图片加载展示而不容易OOM的办
  5. 解决小米、红米及其他 Android(安卓)手机
  6. Android Studio开发Android问题集【持续
  7. Android拨打电话的两种实现方法
  8. Android错误之(Android 6.0)Unable to ad
  9. 开发Android应用程序来使用硬件访问服务
  10. Android 实现视频录制播放