Android自定义标题栏的实例详解

  

<强>,Android自定义标题栏的实例详解

  

开发安卓应用经常会用到自定义标题栏,而有多级页面的情况下还需要给自定义标题栏传递数据。

  

本文要点:

  

自定义标题填充不完整
  自定义标题栏返回按钮的点击事件
  

  

<强>一、代码
  

  

这里先介绍一下流程:
  

  

1。创建一个标题栏布局文件mytitlebar。xml
  2. 在风格。xml中创建mytitlestyle主题
  3.创建类CustomTitleBar
  4. 在需要自定义标题栏的活动的OnCreate方法中实例化CustomTitleBar
  5. 在AndroidManifest。xml对使用了自定义标题栏的活动定义主题

  

1。定义一个自定义的标题栏布局mytitlebar.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;使用   android: id=" @ + id/re_title " xmlns: android=" http://schemas.android.com/apk/res/android "   android: layout_width="宽和"   android: layout_height=" 50 dp "//定义自定义标题栏的高度   android:背景=" @color/start_background”   面向android:="水平"比;      & lt; ImageButton   android: scaleType=" fitXY "   android: layout_alignParentLeft=" true "   android: layout_centerVertical=" true "   android: layout_marginLeft=" 10 dp”   android: id=癅 + id/bt_back”   android: layout_width=" 25 dp "   android: layout_height=" 25 dp "   android: src=" https://www.yisu.com/zixun/@drawable left_back "   android:背景=癅color/touming”/比;   & lt; TextView   android: id=癅 + id/mytitle”   android: layout_centerInParent=" true "   android: layout_width=" wrap_content "   android: layout_height=" match_parent "   android:重力="中心"//使文字在整个标题栏的中间   android:输入textColor=" # fff”   android: textSize=" 20 dp/比;      & lt;/使用相对比;      之前      

2。在风格。xml中创建mytitlestyle主题

        & lt; resources>   & lt; !——自定义标题栏父母=" android:主题为“这个属性必须写——比;   & lt;样式名=" mytitlestyle "父=癮ndroid:主题”比;   & lt; !——设置高度,和mytitlebar。xml中保持一致——比;   & lt;项目名称=" android: windowTitleSize "祝辞50 dp   & lt; !——设置内填充为0使自定义标题填充整个标题栏,否则左右两边有空隙——比;   & lt;项目名称=癮ndroid:填充”在0 dp   & lt;/style>   & lt;/resources>   之前      

3。创建类CustomTitleBar

        公开课CustomTitleBar {      mActivity私人活动;//不要使用静态因为有三级页面返回时会报的错/* *   * @param活动   * @param标题   * @see(自定义标题栏)   */公共空间getTitleBar(活动活动,字符串标题){   mActivity=活动;   activity.requestWindowFeature (Window.FEATURE_CUSTOM_TITLE);//指定自定义标题栏的布局文件   activity.setContentView (R.layout.mytitlebar);   activity.getWindow () .setFeatureInt (Window.FEATURE_CUSTOM_TITLE,   R.layout.mytitlebar);//获取自定义标题栏的TextView控件并设置内容为传递过来的字符串   TextView TextView=(TextView) activity.findViewById (R.id.mytitle);   textView.setText(标题);//设置返回按钮的点击事件   ImageButton titleBackBtn=(ImageButton) activity.findViewById (R.id.bt_back);   titleBackBtn.setOnClickListener (new>   公共类食品延伸活动{   @Override   保护空白>//省略了其余部分,android:主题=癅style/mytitlestyle”这句必需写   & lt;活动   android: name=" .food "   android: label=" @string/activity_food”   android:主题=癅style/mytitlestyle”/比;   之前      

<强>二,总结
  

  

使用自定义标题栏的时候,很多人会遇到填充不满,左右两边有空隙以及返回按钮点击事件不响应的问题,这里测试和总结了最为合适的方式解决。
  

  

自定义标题栏填充不满,网上有不少解决方案,有的还比较复杂,我这里直接在定义主题时一个属性就解决了,还比较容易理解。
  

  

自定义标题栏返回按钮点击事件不响应或出错的问题,也是测试了网上的很多代码,用onBackPressed()最为方便,也有人使用完(),其余的OnKeyDown之类的测试未通过。

  

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Android自定义标题栏的实例详解