1. 程式人生 > >優雅的實現Toolbar標題居中

優雅的實現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了