优雅的实现Toolbar标题居中

目前实现一个Toolbar标题栏居中一般是Toolbar布局文件里面添加一个TextView

然而某些情况下我们不想在Toolbar布局文件里面添加一个布局,于是可以这么封装

    private void setTitleCenter(Toolbar toolbar) {
        TextView titleText = new TextView(getActivity());
        titleText.setTextColor(ContextCompat.getColor(getActivity(), R.color.colorWhite));
        titleText.setText(R.string.fragment_task_title_text);
        titleText.setTextSize(18);
        titleText.setGravity(Gravity.CENTER);
        Toolbar.LayoutParams layoutParams = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        titleText.setLayoutParams(layoutParams);
        toolbar.addView(titleText);
    }

Toolbar系统自带的标题居中:

如果不想自己写个TextView,想使用Toolbar系统自带的标题居中,同样也只需要一行代码调用

    public void setTitleCenter(Toolbar toolbar) {
        String title = "title";
        final CharSequence originalTitle = toolbar.getTitle();
        toolbar.setTitle(title);
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof TextView) {
                TextView textView = (TextView) view;
                if (title.equals(textView.getText())) {
                    textView.setGravity(Gravity.CENTER);
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER;
                    textView.setLayoutParams(params);
                }
            }
            toolbar.setTitle(originalTitle);
        }
    }

两种方式任各位大佬选择,只需要调用一行代码

setTitleCenter(toolbar);

OK了

你可能感兴趣的:(Android,移动开发)