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

目录
相关文章
|
Android开发 UED 计算机视觉
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
本文介绍了一款受游戏“金铲铲之战”启发的Android自定义View——线条等待动画的实现过程。通过将布局分为10份,利用`onSizeChanged`测量最小长度,并借助画笔绘制动态线条,实现渐变伸缩效果。动画逻辑通过四个变量控制线条的增长与回退,最终形成流畅的等待动画。代码中详细展示了画笔初始化、线条绘制及动画更新的核心步骤,并提供完整源码供参考。此动画适用于加载场景,提升用户体验。
736 5
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
|
Android开发
Android自定义view之利用PathEffect实现动态效果
本文介绍如何在Android自定义View中利用`PathEffect`实现动态效果。通过改变偏移量,结合`PathEffect`的子类(如`CornerPathEffect`、`DashPathEffect`、`PathDashPathEffect`等)实现路径绘制的动态变化。文章详细解析了各子类的功能与参数,并通过案例代码展示了如何使用`ComposePathEffect`组合效果,以及通过修改偏移量实现动画。最终效果为一个菱形图案沿路径运动,源码附于文末供参考。
249 0
|
Android开发 开发者
Android自定义view之利用drawArc方法实现动态效果
本文介绍了如何通过Android自定义View实现动态效果,重点使用`drawArc`方法完成圆弧动画。首先通过`onSizeChanged`进行测量,初始化画笔属性,设置圆弧相关参数。核心思路是不断改变圆弧扫过角度`sweepAngle`,并调用`invalidate()`刷新View以实现动态旋转效果。最后附上完整代码与效果图,帮助开发者快速理解并实践这一动画实现方式。
293 0
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
267 0
|
XML Java Android开发
Android自定义view之网易云推荐歌单界面
本文详细介绍了如何通过自定义View实现网易云音乐推荐歌单界面的效果。首先,作者自定义了一个圆角图片控件`MellowImageView`,用于绘制圆角矩形图片。接着,通过将布局放入`HorizontalScrollView`中,实现了左右滑动功能,并使用`ViewFlipper`添加图片切换动画效果。文章提供了完整的代码示例,包括XML布局、动画文件和Java代码,最终展示了实现效果。此教程适合想了解自定义View和动画效果的开发者。
517 65
Android自定义view之网易云推荐歌单界面
|
XML 前端开发 Android开发
一篇文章带你走近Android自定义view
这是一篇关于Android自定义View的全面教程,涵盖从基础到进阶的知识点。文章首先讲解了自定义View的必要性及简单实现(如通过三个构造函数解决焦点问题),接着深入探讨Canvas绘图、自定义属性设置、动画实现等内容。还提供了具体案例,如跑马灯、折线图、太极图等。此外,文章详细解析了View绘制流程(measure、layout、draw)和事件分发机制。最后延伸至SurfaceView、GLSurfaceView、SVG动画等高级主题,并附带GitHub案例供实践。适合希望深入理解Android自定义View的开发者学习参考。
939 84
|
前端开发 Android开发 UED
讲讲Android为自定义view提供的SurfaceView
本文详细介绍了Android中自定义View时使用SurfaceView的必要性和实现方式。首先分析了在复杂绘制逻辑和高频界面更新场景下,传统View可能引发卡顿的问题,进而引出SurfaceView作为解决方案。文章通过Android官方Demo展示了SurfaceView的基本用法,包括实现`SurfaceHolder.Callback2`接口、与Activity生命周期绑定、子线程中使用`lockCanvas()`和`unlockCanvasAndPost()`方法完成绘图操作。
342 3
|
Android开发 开发者
Android自定义view之围棋动画(化繁为简)
本文介绍了Android自定义View的动画实现,通过两个案例拓展动态效果。第一个案例基于`drawArc`方法实现单次动画,借助布尔值控制动画流程。第二个案例以围棋动画为例,从简单的小球直线运动到双向变速运动,最终实现循环动画效果。代码结构清晰,逻辑简明,展示了如何化繁为简实现复杂动画,帮助读者拓展动态效果设计思路。文末提供完整源码,适合初学者和进阶开发者学习参考。
235 0
Android自定义view之围棋动画(化繁为简)
|
Java Android开发 开发者
Android自定义view之围棋动画
本文详细介绍了在Android中自定义View实现围棋动画的过程。从测量宽高、绘制棋盘背景,到创建固定棋子及动态棋子,最后通过属性动画实现棋子的移动效果。文章还讲解了如何通过自定义属性调整棋子和棋盘的颜色及动画时长,并优化视觉效果,如添加渐变色让白子更明显。最终效果既可作为围棋动画展示,也可用作加载等待动画。代码完整,适合进阶开发者学习参考。
298 0
|
传感器 Android开发 开发者
Android自定义view之3D正方体
本文介绍了如何通过手势滑动操作实现3D正方体的旋转效果,基于Android自定义View中的GLSurfaceView。相较于使用传感器控制,本文改用事件分发机制(onTouchEvent)处理用户手势输入,调整3D正方体的角度。代码中详细展示了TouchSurfaceView的实现,包括触控逻辑、OpenGL ES绘制3D正方体的核心过程,以及生命周期管理。适合对Android 3D图形开发感兴趣的开发者学习参考。
270 0

热门文章

最新文章