Android自定义标题栏
16lz
2021-12-04
Android自带的标题栏样式非常的单调,有时候会想要自定义自己的标题栏样式,但是Android默认是不允许设定标题栏样式的,所以需要手动去设置它:
首先,在java代码onCreate方法中【代码的顺序必须按照以下排,否则会没有效果】:
super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //设置自定义标题栏时必须先指定此变量setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title); //设置标题栏布局为自己的自定义布局
其中,requestWindowFeature还有其它许多变量:
DEFAULT_FEATURES:系统默认状态,一般不需要指定
FEATURE_CONTEXT_MENU:启用ContextMenu,默认该项已启用,一般无需指定
FEATURE_CUSTOM_TITLE:自定义标题。当需要自定义标题时必须指定。如:标题是一个按钮时
FEATURE_INDETERMINATE_PROGRESS:不确定的进度
FEATURE_LEFT_ICON:标题栏左侧的图标
FEATURE_NO_TITLE:无标题
FEATURE_OPTIONS_PANEL:启用“选项面板”功能,默认已启用。
FEATURE_PROGRESS:进度指示器功能
FEATURE_RIGHT_ICON:标题栏右侧的图标
接着自定义标题栏的布局文件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="wrap_content" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/app_name" android:gravity="center"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="设置"/></LinearLayout>
直到这一步,我们只是换了标题栏的布局,并不能改变它的高度或者背景颜色,因此可以通过再定义style来设置:
在style.xml中:
<style name ="CustomWindowTitleBackground"> <item name ="android:background">#1F497D</item> </style> <style name="title" parent="android:Theme"> <item name ="android:windowTitleSize">45dp</item> <item name ="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item> </style>
最后,还要将该样式设置到Activity中,在AndroidManifest.xml中:
更多相关文章
- TextView属性大全
- android:configChanges属性
- Android在代码中设置drawableLeft(Right/Top/Bottom)
- Android常用控件总结
- Android:shape的使用详解(2)
- ScrollView常用属性汇总
- (Android)react-native更改状态栏文字和图标颜色
- Android利用Fiddler进行网络数据抓包
- textView 属性总结