Android 自定义view实现TopBar效果

发布时间 - 2026-01-11 03:29:23    点击率:

本文实例为大家分享了Android自定义view实现TopBar的具体代码,供大家参考,具体内容如下

布局文件

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:id="@+id/activity_main" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:paddingBottom="@dimen/activity_vertical_margin" 
  android:paddingLeft="@dimen/activity_horizontal_margin" 
  android:paddingRight="@dimen/activity_horizontal_margin" 
  android:paddingTop="@dimen/activity_vertical_margin" 
  tools:context="com.bwie.test.MainActivity"> 
 
  <com.bwie.test.MyView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:lt="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/titlebar" 
    android:layout_width="match_parent" 
    android:layout_height="60dp" 
    lt:leftButtonText="返回" 
    lt:leftButtonTextColor="@android:color/white" 
    lt:leftButtonTextSize="8sp" 
    lt:buttonBgColor="#4556ec" 
    lt:titleText="标题" 
    lt:titleColor="@android:color/white" 
    lt:titleSize="8sp" 
    lt:rightButtonText="完成" 
    lt:rightButtonTextColor="@android:color/white" 
    lt:rightButtonTextSize="8sp" 
    android:background="#47ea10" 
    android:padding="10sp" 
    > 
  </com.bwie.test.MyView> 
</RelativeLayout> 

自定义属性attrs.xml文件

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
  <declare-styleable name="Titlebar"> 
    <attr name="leftButtonText" format="string|reference"></attr> 
    <attr name="leftButtonTextColor" format="color|reference"></attr> 
    <attr name="leftButtonTextSize" format="dimension|reference"></attr> 
    <attr name="leftButtonImage" format="color|reference"></attr> 
    <attr name="buttonBgColor" format="color"/> 
 
    <attr name="titleText" format="string|reference"></attr> 
    <attr name="titleColor" format="color|reference"></attr> 
    <attr name="titleSize" format="dimension|reference"></attr> 
 
    <attr name="rightButtonText" format="string|reference"></attr> 
    <attr name="rightButtonTextColor" format="color|reference"></attr> 
    <attr name="rightButtonTextSize" format="dimension|reference"></attr> 
    <attr name="rightButtonImage" format="color|reference"></attr> 
 
 
  </declare-styleable> 
 
</resources> 

自定义View的Class类

public class MyView extends RelativeLayout{ 
 
  private String mLeftButtonText; 
  private int mLeftButtonTextColor; 
  private float mLeftButtonSize; 
  private Drawable mLeftButtonImage; 
  private String mTitleButtonText; 
  private int mTitleButtonTextColor; 
  private float mTitleButtonSize; 
  private String mRightButtonText; 
  private int mRightButtonTextColor; 
  private float mRightButtonSize; 
  private Drawable mRightButtonImage; 
  private TextView mRightTextView; 
  private TextView titleTextView; 
  private ImageView mLeftButton; 
  private TextView mLeftTextView; 
  private ImageView mRightButton; 
  int buttonBgColor; 
  public MyView(Context context) { 
    this(context,null); 
  } 
 
  public MyView(Context context, AttributeSet attrs) { 
    this(context, attrs,0); 
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Titlebar); 
    buttonBgColor = typedArray.getColor(R.styleable.Titlebar_buttonBgColor,Color.BLUE); 
 
//左侧的按钮 
    mLeftButtonText = typedArray.getString(R.styleable.Titlebar_leftButtonText); 
    mLeftButtonTextColor = typedArray.getColor(R.styleable.Titlebar_leftButtonTextColor, Color.GRAY); 
    mLeftButtonSize = typedArray.getDimension(R.styleable.Titlebar_leftButtonTextSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); 
    mLeftButtonImage = typedArray.getDrawable(R.styleable.Titlebar_leftButtonImage); 
//中间的按钮 
    mTitleButtonText = typedArray.getString(R.styleable.Titlebar_titleText); 
    mTitleButtonTextColor = typedArray.getColor(R.styleable.Titlebar_titleColor, Color.GRAY); 
    mTitleButtonSize = typedArray.getDimension(R.styleable.Titlebar_titleSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); 
//右侧的按钮 
    mRightButtonText = typedArray.getString(R.styleable.Titlebar_rightButtonText); 
    mRightButtonTextColor = typedArray.getColor(R.styleable.Titlebar_rightButtonTextColor, Color.GRAY); 
    mRightButtonSize = typedArray.getDimension(R.styleable.Titlebar_rightButtonTextSize, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); 
    mRightButtonImage = typedArray.getDrawable(R.styleable.Titlebar_rightButtonImage); 
 
    typedArray.recycle();//回收 
    /*调用方法*/ 
    initView(context); 
  } 
 
  public MyView(Context context, AttributeSet attrs, int defStyleAttr) { 
    this(context, attrs, defStyleAttr,0); 
  } 
 
  public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
    super(context, attrs, defStyleAttr, defStyleRes); 
  } 
  /*构建按钮*/ 
  private void initView(Context context) { 
 
    if(mLeftButtonImage == null & mLeftButtonText != null){ 
      // 当用户没有设置左侧按钮图片并设置了左侧的按钮文本属性时--添加左侧文本按钮 
      mLeftTextView = new TextView(context); 
      mLeftTextView.setText(mLeftButtonText); 
      mLeftTextView.setTextColor(mLeftButtonTextColor); 
      mLeftTextView.setTextSize(mLeftButtonSize); 
      mLeftTextView.setBackgroundColor(buttonBgColor); 
      RelativeLayout.LayoutParams leftParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 
      leftParams.addRule(RelativeLayout.CENTER_VERTICAL); 
      addView(mLeftTextView, leftParams); 
    }else if(mLeftButtonImage != null){ 
      // 添加左侧图片按钮 
      RelativeLayout.LayoutParams leftParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 
      leftParams.addRule(RelativeLayout.CENTER_VERTICAL); 
      mLeftButton = new ImageView(context); 
      mLeftButton.setImageDrawable(mLeftButtonImage); 
      addView(mLeftButton, leftParams); 
    } 
 
    if(mTitleButtonText!=null){ 
      // 添加中间标题 
      titleTextView = new TextView(context); 
      titleTextView.setText(mTitleButtonText); 
      titleTextView.setTextColor(mTitleButtonTextColor); 
      titleTextView.setTextSize(mTitleButtonSize); 
      RelativeLayout.LayoutParams titleTextViewParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      titleTextViewParams.addRule(RelativeLayout.CENTER_IN_PARENT); 
      addView(titleTextView,titleTextViewParams); 
    } 
 
    if(mRightButtonImage == null & mRightButtonText != null){ 
      // 当用户没有设置右侧按钮图片并设置了左侧的按钮文本属性时--添加右侧文本按钮 
      mRightTextView = new TextView(context); 
      mRightTextView.setText(mRightButtonText); 
      mRightTextView.setTextColor(mRightButtonTextColor); 
       mRightTextView.setTextSize(mRightButtonSize); 
      mRightTextView.setBackgroundColor(buttonBgColor); 
      RelativeLayout.LayoutParams rightParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
      rightParams.addRule(RelativeLayout.CENTER_VERTICAL); 
      addView(mRightTextView,rightParams); 
    }else if(mRightButtonImage != null){ 
      // 添加右侧图片按钮 
      RelativeLayout.LayoutParams rightParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
      rightParams.addRule(RelativeLayout.CENTER_VERTICAL); 
      mRightButton = new ImageView(context); 
      mRightButton.setImageDrawable(mRightButtonImage); 
      addView(mRightButton, rightParams); 
    } 
  } 
  /*监听事件*/ 
  public interface OnButtonClickListener{ 
    void onLeftClick(); 
    void onRightClick(); 
  } 
  /*点击事件*/ 
  public void setOnButtonClickListener(final OnButtonClickListener onButtonClickListener) { 
    if(onButtonClickListener !=null){ 
      if(mLeftTextView != null){ 
        mLeftTextView.setOnClickListener(new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
            onButtonClickListener.onLeftClick(); 
          } 
        }); 
      } 
      /*按钮*/ 
      if(mLeftButton != null){ 
        mLeftButton.setOnClickListener(new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
            onButtonClickListener.onLeftClick(); 
          } 
        }); 
      } 
      if(mRightTextView != null){ 
        mRightTextView.setOnClickListener(new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
            onButtonClickListener.onRightClick(); 
          } 
        }); 
      } 
      /*按钮*/ 
      if(mRightButton != null){ 
        mRightButton.setOnClickListener(new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
            onButtonClickListener.onRightClick(); 
          } 
        }); 
      } 
    } 
  } 

Main方法的代码调用自定义的类和点击事件

public class MainActivity extends AppCompatActivity { 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
 
    /*找到控件*/ 
    MyView Myview = (MyView) findViewById(R.id.titlebar); 
    /*点击事件*/ 
    Myview.setOnButtonClickListener(new MyView.OnButtonClickListener() { 
      @Override 
      public void onLeftClick() { 
        Toast.makeText(MainActivity.this,"左侧按钮被点击了",Toast.LENGTH_SHORT).show(); 
      } 
 
      @Override 
      public void onRightClick() { 
        Toast.makeText(MainActivity.this,"右侧按钮被点击了",Toast.LENGTH_SHORT).show(); 
      } 
    }); 
 
  } 
} 

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# Android  # view  # TopBar  # android之listview悬浮topBar效果  # 自定义  # 大家分享  # 具体内容  # 大家多多  # background  # rightButtonTextSize  # rightButtonText  # rightButtonTextColor  # resources  # declare  # attrs  # padding  # titleSize  # white  # leftButtonTextSize  # color  # leftButtonText  # leftButtonTextColor  # sp  # titleText 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?  Laravel Asset编译怎么配置_Laravel Vite前端构建工具使用  Swift开发中switch语句值绑定模式  Laravel队列由Redis驱动怎么配置_Laravel Redis队列使用教程  香港服务器选型指南:免备案配置与高效建站方案解析  网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?  网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?  Laravel如何实现邮件验证激活账户_Laravel内置MustVerifyEmail接口配置【步骤】  JS弹性运动实现方法分析  如何获取上海专业网站定制建站电话?  Laravel如何使用.env文件管理环境变量?(最佳实践)  重庆市网站制作公司,重庆招聘网站哪个好?  HTML5建模怎么导出为FBX格式_FBX格式兼容性及导出步骤【指南】  新三国志曹操传主线渭水交兵攻略  如何快速启动建站代理加盟业务?  如何用PHP快速搭建高效网站?分步指南  七夕网站制作视频,七夕大促活动怎么报名?  Win11怎么关闭资讯和兴趣_Windows11任务栏设置隐藏小组件  如何在服务器上配置二级域名建站?  想要更高端的建设网站,这些原则一定要坚持!  专业型网站制作公司有哪些,我设计专业的,谁给推荐几个设计师兼职类的网站?  黑客如何利用漏洞与弱口令入侵网站服务器?  Laravel项目如何进行性能优化_Laravel应用性能分析与优化技巧大全  iOS发送验证码倒计时应用  浅述节点的创建及常见功能的实现  Internet Explorer官网直接进入 IE浏览器在线体验版网址  QQ浏览器网页版登录入口 个人中心在线进入  阿里云网站搭建费用解析:服务器价格与建站成本优化指南  如何快速生成ASP一键建站模板并优化安全性?  C++时间戳转换成日期时间的步骤和示例代码  laravel怎么配置Redis作为缓存驱动_laravel Redis缓存配置教程  html5如何实现懒加载图片_ intersectionobserver api用法【教程】  如何在阿里云购买域名并搭建网站?  如何在建站之星网店版论坛获取技术支持?  惠州网站建设制作推广,惠州市华视达文化传媒有限公司怎么样?  Win11怎么关闭专注助手 Win11关闭免打扰模式设置【操作】  Laravel如何为API编写文档_Laravel API文档生成与维护方法  linux写shell需要注意的问题(必看)  Laravel如何使用Eloquent ORM进行数据库操作?(CRUD示例)  北京企业网站设计制作公司,北京铁路集团官方网站?  Laravel Telescope怎么调试_使用Laravel Telescope进行应用监控与调试  Linux虚拟化技术教程_KVMQEMU虚拟机安装与调优  大学网站设计制作软件有哪些,如何将网站制作成自己app?  Laravel如何实现多语言支持_Laravel本地化与国际化(i18n)配置教程  EditPlus中的正则表达式 实战(1)  Laravel Sail是什么_基于Docker的Laravel本地开发环境Sail入门  智能起名网站制作软件有哪些,制作logo的软件?  如何快速完成中国万网建站详细流程?  如何用西部建站助手快速创建专业网站?  Laravel如何处理CORS跨域请求?(配置示例)