Android 自定义ToolBar并沉浸式

简介:   ToolBar是Android 5.0推出的一个新的导航控件用于取代之前的ActionBar,由于其高度的可定制性、灵活性、具有Material Design风格等优点,越来越多的App也用上了ToolBar。

  ToolBar是Android 5.0推出的一个新的导航控件用于取代之前的ActionBar,由于其高度的可定制性、灵活性、具有Material Design风格等优点,越来越多的App也用上了ToolBar。
  沉浸式状态栏是从android Kitkat(Android 4.4)开始出现的,它可以被设置成与APP顶部相同的颜色,这就使得切换APP时,整个界面就好似切换到了与APP相同的风格样式一样。

依赖包:

  Toolbar, implementation 'androidx.appcompat:appcompat:1.1.0'
  沉浸式, implementation 'com.gyf.immersionbar:immersionbar:3.0.0'

1、自定义Toolbar步骤:

1)、定义 /values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="TextAppearance_TitleBar_Title" parent="TextAppearance.AppCompat.Toolbar.Title">
    ...
    </style>

    <style name="TextAppearance_TitleBar_subTitle" parent="TextAppearance.AppCompat.Toolbar.Subtitle">
      ....
    </style>
</resources>

2)、自定义toolbar 继承 androidx.appcompat.widget.Toolbar

public class CustomToolBar extends Toolbar {
    private TextView mCenterTitle;
    private ImageView mCenterIcon; //中心icon
    private TextView mLeftText;
    private ImageButton mLeftIcon; 
    private TextView mSettingText;
    private ImageButton mSettingIcon;

    public CustomToolBar(Context context) {
        super(context);
    }

    public CustomToolBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomToolBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

  
    public void setLeftText(@StringRes int id) {
        setLeftText(this.getContext().getText(id));
    }

  
    public CustomToolBar setLeftText(CharSequence text) {
        Context context = this.getContext();
        if (this.mLeftText == null) {
            this.mLeftText = new TextView(context);
            this.mLeftText.setGravity(Gravity.CENTER_VERTICAL);
            this.mLeftText.setSingleLine();
//            this.mLeftText.setEllipsize(TextUtils.TruncateAt.END);
            setLeftTextAppearance(getContext(), R.style.TextAppearance_TitleBar_subTitle);
            //textView in left
//            this.addMyView(this.mLeftText, Gravity.START);
            int i = dp2px(this, 16);
            this.addMyView(this.mLeftText, Gravity.START, 0, 0, i, 0, 48);
        }
        mLeftText.setText(text);
        return this;
    }

    public void setLeftTextAppearance(Context context, @StyleRes int resId) {
        if (this.mLeftText != null) {
            this.mLeftText.setTextAppearance(context, resId);
        }
    }

    public void setLeftTextColor(@ColorInt int color) {
        if (this.mLeftText != null) {
            this.mLeftText.setTextColor(color);
        }
    }

    public void setLeftTextOnClickListener(OnClickListener listener) {
        if (mLeftText != null) {
            mLeftText.setOnClickListener(listener);
        }
    }

    public CustomToolBar setLeftIcon(@DrawableRes int resId) {
        return setLeftIcon(ContextCompat.getDrawable(this.getContext(), resId));
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public CustomToolBar setLeftIcon(Drawable drawable) {
        Context context = this.getContext();
        if (this.mLeftIcon == null) {
            this.mLeftIcon = new ImageButton(context);
             ...

            this.addMyView(this.mLeftIcon, Gravity.START);
        } else {
            if (mLeftIcon.getVisibility() != VISIBLE) {
                mLeftIcon.setVisibility(VISIBLE);
            }
        }
        if (mLeftText != null && mLeftText.getVisibility() != GONE) {
            mLeftText.setVisibility(GONE);
        }
        mLeftIcon.setImageDrawable(drawable);
        return this;
    }

    public void setLeftIconOnClickListener(OnClickListener listener) {
        if (mLeftIcon != null) {
            mLeftIcon.setOnClickListener(listener);
        }
    }

    public void setLeftIconVisibility(int visibility) {
        if (mLeftIcon != null) {
            mLeftIcon.setVisibility(visibility);
        }
    }

 
    public CustomToolBar setMyCenterTitle(@StringRes int id, boolean center) {
        return setMyCenterTitle(this.getContext().getText(id), center);
    }

  
    public void setMyCenterTitle(@StringRes int Rid) {
        setMyCenterTitle(this.getContext().getText(Rid));
    }

   public void setMyCenterTitle(CharSequence text) {
        Context context = this.getContext();
        if (this.mCenterTitle == null) {
            this.mCenterTitle = new TextView(context);
          ...

        } else {
            if (this.mCenterTitle.getVisibility() != VISIBLE) {
                mCenterTitle.setVisibility(VISIBLE);
            }
        }
        if (mCenterIcon != null && mCenterIcon.getVisibility() != GONE) {
            mCenterIcon.setVisibility(GONE);
        }
    
      ...

    }
    public CustomToolBar setMyCenterTitle(CharSequence text, boolean center) {
        Context context = this.getContext();
        if (this.mCenterTitle == null) {
            this.mCenterTitle = new TextView(context);

           ...

        } else {
            if (this.mCenterTitle.getVisibility() != VISIBLE) {
                mCenterTitle.setVisibility(VISIBLE);
            }
        }
        if (mCenterIcon != null && mCenterIcon.getVisibility() != GONE) {
            mCenterIcon.setVisibility(GONE);
        }
   
        if (!center) {
            setTitle(text);
            setTitleTextColor(getResources().getColor(R.color.black));
        } else {
            mCenterTitle.setText(text);
            mCenterTitle.setTextColor(getResources().getColor(R.color.black));
            mCenterTitle.setTextSize(16);
        }
        return this;
    }

    public void setMyCenterTextAppearance(Context context, @StyleRes int resId) {
        if (this.mCenterTitle != null) {
            this.mCenterTitle.setTextAppearance(context, resId);
        }
    }

    public void setMyCenterTextColor(@ColorInt int color) {
        if (this.mCenterTitle != null) {
            this.mCenterTitle.setTextColor(color);
        }
    }

    public void setMyCenterTextOnClickListener(OnClickListener listener) {
        if (mCenterTitle != null) {
            mCenterTitle.setOnClickListener(listener);
        }
    }

 
    public void setMyCenterIcon(@DrawableRes int resId) {
        setMyCenterIcon(ContextCompat.getDrawable(this.getContext(), resId));
    }

    public void setMyCenterIcon(Drawable drawable) {
        Context context = this.getContext();
        if (this.mCenterIcon == null) {

         ...

        } else {
            if (mCenterIcon.getVisibility() != VISIBLE) {
                mCenterIcon.setVisibility(VISIBLE);
            }
        }
        if (mCenterTitle != null && mCenterTitle.getVisibility() != GONE) {
            mCenterTitle.setVisibility(GONE);
        }
     
        setTitle("");
        mCenterIcon.setImageDrawable(drawable);
    }

  
    public void setMySettingText(@StringRes int Rid) {
        setMySettingText(this.getContext().getText(Rid));
    }

    public void setMySettingText(CharSequence text) {
        Context context = this.getContext();
        if (this.mSettingText == null) {

           ...

        } else {
            if (mSettingText.getVisibility() != VISIBLE) {
                mSettingText.setVisibility(VISIBLE);
            }
        }
        if (mSettingIcon != null && mSettingIcon.getVisibility() != GONE) {
            mSettingIcon.setVisibility(GONE);
        }
        mSettingText.setText(text);
        mSettingText.setTextSize(14);
        mSettingText.setTextColor(getResources().getColor(R.color.toolbar_title));

    }

    public void setMySettingTextAppearance(Context context, @StyleRes int resId) {
        if (mSettingText != null) {
            mSettingText.setTextAppearance(context, resId);
        }
    }

    public void setMySettingTextColor(@ColorInt int color) {
        if (mSettingText != null) {
            mSettingText.setTextColor(color);
        }
    }

    public void setSettingTextOnClickListener(OnClickListener listener) {
        if (mSettingText != null) {
            mSettingText.setOnClickListener(listener);
        }
    }

    public CustomToolBar setMySettingIcon(@DrawableRes int resId) {
        return setMySettingIcon(ContextCompat.getDrawable(this.getContext(), resId));
//        ViewConfiguration.get(this.getContext()).getScaledTouchSlop();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public CustomToolBar setMySettingIcon(Drawable drawable) {
        Context context = this.getContext();
        if (this.mSettingIcon == null) {

          ...

        } else {
            if (mSettingIcon.getVisibility() != VISIBLE) {
                mSettingIcon.setVisibility(VISIBLE);
            }
        }
        if (mSettingText != null && mSettingText.getVisibility() != GONE) {
            mSettingText.setVisibility(GONE);
        }
        mSettingIcon.setImageDrawable(drawable);
        return this;
    }

    public void setSettingIconOnClickListener(OnClickListener listener) {
        if (mSettingIcon != null) {
            mSettingIcon.setOnClickListener(listener);
        }
    }

    private void addSimpleView(View v, int gravity) {
        addSimpleView(v, gravity, 0, 0, 0, 0);
    }

    private void addSimpleView(View v, int gravity, int left, int top, int right, int bottom) {
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, gravity);
        lp.setMargins(left, top, right, bottom);
        this.addView(v, lp);
    }

  
    private void addMyView(View v, int gravity) {

        addMyView(v, gravity, 0, 0, dp2px(this, 16), 0);
    }

    private void addMyView(View v, int gravity, int left, int top, int right, int bottom) {
        LayoutParams lp = new LayoutParams(dp2px(this, 20),
                dp2px(this, 20), gravity);
        lp.setMargins(left, top, right, bottom);
        this.addView(v, lp);
    }

    private void addMyView(View v, int gravity, int left, int top, int right, int bottom, int width) {
        LayoutParams lp = new LayoutParams(dp2px(this, width),
                20, gravity);
        lp.setMargins(left, top, right, bottom);
        this.addView(v, lp);
    }


    public CustomToolBar setCenterTitleWithImg(CharSequence text, Drawable drawable, boolean center) {
        Context context = this.getContext();
        if (this.mCenterTitle == null) {
            this.mCenterTitle = new TextView(context);

           ...

            if (this.mCenterTitle.getVisibility() != VISIBLE) {
                mCenterTitle.setVisibility(VISIBLE);
            }
        }

        if (this.mCenterIcon == null) {
            this.mCenterIcon = new ImageView(context);

            ...

        } else {
            if (mCenterIcon.getVisibility() != VISIBLE) {
                mCenterIcon.setVisibility(VISIBLE);
            }
        }

        mCenterTitle.setTextSize(18);
        mCenterTitle.setTextColor(getResources().getColor(R.color.black));
        mCenterTitle.setText(text);
        mCenterIcon.setImageDrawable(drawable);

        return this;
    }

    public void setCenterTitleWithImgOnClickListener(OnClickListener listener) {
        if (mCenterTitle != null) {
            ((View) mCenterTitle.getParent()).setOnClickListener(listener);
        }
    }
}

2、自定义Toolbar使用

1)、res/layout创建布局文件

      <?xml version="1.0" encoding="utf-8"?>
frameLabelStart--frameLabelEnd 

2)、在布局中使用

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:binding="http://schemas.android.com/tools">
    <data>
        <variable
            name="viewModel"
            type="com.android.playandroid.viewmodel.LoginViewModel" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bkg"
        android:orientation="vertical">

        <include
            layout="@layout/title_layout"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
         ...
    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

3)、代码中使用

##### a、初始化:

    mBinding.root.toolbar.setNavigationIcon(R.mipmap.register_close)
    mBinding.root.toolbar.setMyCenterTitle(getString(R.string.register), true)
    mBinding.root.toolbar.setMySettingText(getString(R.string.login))

##### b、点击事件:

   mBinding.root.toolbar.setNavigationOnClickListener {
        ....
    }
    mBinding.root.toolbar.setSettingTextOnClickListener {
       ...
}

4)、沉浸式,设置toolbar背景颜色、文字颜色,一般写在基类

 protected open fun initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this)
        if (toolbar != null) {
            mImmersionBar.titleBar(toolbar)
        }
        mImmersionBar.statusBarDarkFont(true)
    //    mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init()
      //  mImmersionBar.init()
        
       ImmersionBar.with(this).init()
    }

注意:

1、配置整个app的toolbar风格,在/value/styles.xml文件修改代码

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    
        <item name="colorPrimary">@android:color/white</item>
        <item name="colorPrimaryDark">@android:color/white</item>
        <item name="colorAccent">@android:color/white</item>

      ...

    </style>

#### 2、修改了 toolbar的高度 ,怎么让navigationIcon显示在toolbar中心?
  只要设置如下,即可:android:minHeight="@dimen/toolbar_height"

3、toolbar布局文件位置

  如果在commonlibrary目录创建该文件,在app 下还需要复制一份,因为在app 使用toolbar,kotlin-android-extensions引用不到commonlibrary目录下的布局文件。

代码Github:https://github.com/AlbertShen0211/PlayAndroid

目录
相关文章
|
24天前
|
存储 Shell Android开发
基于Android P,自定义Android开机动画的方法
本文详细介绍了基于Android P系统自定义开机动画的步骤,包括动画文件结构、脚本编写、ZIP打包方法以及如何将自定义动画集成到AOSP源码中。
42 2
基于Android P,自定义Android开机动画的方法
|
22天前
|
供应链 物联网 区块链
未来触手可及:探索新兴技术的趋势与应用安卓开发中的自定义视图:从基础到进阶
【8月更文挑战第30天】随着科技的飞速发展,新兴技术如区块链、物联网和虚拟现实正在重塑我们的世界。本文将深入探讨这些技术的发展趋势和应用场景,带你领略未来的可能性。
|
23天前
|
测试技术 Android开发 Python
探索软件测试的艺术:从基础到高级安卓应用开发中的自定义视图
【8月更文挑战第29天】在软件开发的世界中,测试是不可或缺的一环。它如同艺术一般,需要精细的技巧和深厚的知识。本文旨在通过浅显易懂的语言,引领读者从软件测试的基础出发,逐步深入到更复杂的测试策略和工具的使用,最终达到能够独立进行高效测试的水平。我们将一起探索如何通过不同的测试方法来确保软件的质量和性能,就像艺术家通过不同的色彩和笔触来完成一幅画作一样。
|
1天前
|
Android开发 开发者
安卓开发中的自定义视图:从入门到精通
【9月更文挑战第19天】在安卓开发的广阔天地中,自定义视图是一块充满魔力的土地。它不仅仅是代码的堆砌,更是艺术与科技的完美结合。通过掌握自定义视图,开发者能够打破常规,创造出独一无二的用户界面。本文将带你走进自定义视图的世界,从基础概念到实战应用,一步步展示如何用代码绘出心中的蓝图。无论你是初学者还是有经验的开发者,这篇文章都将为你打开一扇通往创意和效率的大门。让我们一起探索自定义视图的秘密,将你的应用打造成一件艺术品吧!
18 10
|
6天前
|
XML 编解码 Android开发
安卓开发中的自定义视图控件
【9月更文挑战第14天】在安卓开发中,自定义视图控件是一种高级技巧,它可以让开发者根据项目需求创建出独特的用户界面元素。本文将通过一个简单示例,引导你了解如何在安卓项目中实现自定义视图控件,包括创建自定义控件类、处理绘制逻辑以及响应用户交互。无论你是初学者还是有经验的开发者,这篇文章都会为你提供有价值的见解和技巧。
14 3
|
7天前
|
前端开发 Android开发 开发者
安卓应用开发中的自定义视图基础
【9月更文挑战第13天】在安卓开发的广阔天地中,自定义视图是一块神奇的画布,它允许开发者将想象力转化为用户界面的创新元素。本文将带你一探究竟,了解如何从零开始构建自定义视图,包括绘图基础、触摸事件处理,以及性能优化的实用技巧。无论你是想提升应用的视觉吸引力,还是追求更流畅的交互体验,这里都有你需要的金钥匙。
|
10天前
|
缓存 搜索推荐 Android开发
安卓应用开发中的自定义View组件实践
【9月更文挑战第10天】在安卓开发领域,自定义View是提升用户体验和实现界面个性化的重要手段。本文将通过一个实际案例,展示如何在安卓项目中创建和使用自定义View组件,包括设计思路、实现步骤以及可能遇到的问题和解决方案。文章不仅提供了代码示例,还深入探讨了自定义View的性能优化技巧,旨在帮助开发者更好地掌握这一技能。
|
22天前
|
XML 搜索推荐 Android开发
安卓开发中的自定义View组件实践
【8月更文挑战第30天】探索Android世界,自定义View是提升应用界面的关键。本文以简洁的语言带你了解如何创建自定义View,从基础到高级技巧,一步步打造个性化的UI组件。
|
24天前
|
Android开发
Android在rootdir根目录创建自定义目录和挂载点的方法
本文介绍了在Android高通平台的根目录下创建自定义目录和挂载点的方法,通过修改Android.mk文件并使用`LOCAL_POST_INSTALL_CMD`变量在编译过程中添加目录,最终在ramdisk.img的系统根路径下成功创建了`/factory/bin`目录。
49 1
|
14天前
|
前端开发 搜索推荐 Android开发
探索安卓开发中的自定义视图##
【9月更文挑战第6天】 在安卓应用开发的世界里,自定义视图如同绘画艺术中的色彩,它们为界面设计增添了无限可能。通过掌握自定义视图的绘制技巧,开发者能够创造出既符合品牌形象又提升用户体验的独特界面元素。本文将深入浅出地介绍如何从零开始构建一个自定义视图,包括基础框架搭建、关键绘图方法实现、事件处理机制以及性能优化策略。准备好让你的安卓应用与众不同了吗?让我们开始吧! ##