您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Toolbar获取自带TitleTextView和动态设置高度

Toolbar获取自带TitleTextView和动态设置高度

来源:二三娱乐

使用Toolbar,有时我们需要在代码中对TitelTextView和Toolbar高度进行设置,但Toolbar未留对应接口,所以只能自己想办法。

一、获取TitleTextView

这里我们使用反射机制获取。

 /**
     * 获取TitleTextView
     * @return
     */
    protected TextView getTitleTextView(){
        try {
            Field field = Toolbar.class.getDeclaredField("mTitleTextView");
            field.setAccessible(true);
            return (TextView) field.get(vToolbar);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

二、动态设置Toolbar高度

看到过别人是这样写的:

public void reSetToolbarHeight(Toolbar toolbar) {
    try {
        Field f = Toolbar.class.getDeclaredField("mNavButtonView");
        f.setAccessible(true);
        ImageButton mNavButtonView = (ImageButton) f.get(toolbar);
        if (mNavButtonView != null) {
            Toolbar.LayoutParams l = (Toolbar.LayoutParams) mNavButtonView.getLayoutParams();
            l.gravity = Gravity.CENTER_VERTICAL;
            l.height += 100;
            l.width += 100;
            mNavButtonView.setLayoutParams(l);
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

一眼看出来这里使用了反射的方式,对Toolbar子控件重新定义高度来实现。
对于反射的弊端相信大家都清楚,所以不推荐使用,这里有更简便的方法:

/**
     * 重置Toolbar高度
     * @param height
     */
    protected void setToolbarHeight(int height){
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
        vToolbar.setLayoutParams(params);
    }

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务