Getting ActionBar Title TextView with AppCompat v7 r21

前端 未结 5 946
长情又很酷
长情又很酷 2020-12-09 04:45

I have a library that requires to use the color of the TextView for the ActionBar title. Prior to AppCompat v7 r21 I could just findViewById(

5条回答
  •  情深已故
    2020-12-09 05:20

    No need for creating your own TextView, just loop through toolbar children to get the built-in title.

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    
    // loop through all toolbar children right after setting support 
    // action bar because the text view has no id assigned
    
    // also make sure that the activity has some title here
    // because calling setText() with an empty string actually
    // removes the text view from the toolbar
    
    TextView toolbarTitle = null;
    for (int i = 0; i < toolbar.getChildCount(); ++i) {
        View child = toolbar.getChildAt(i);
    
        // assuming that the title is the first instance of TextView
        // you can also check if the title string matches
        if (child instanceof TextView) {
            toolbarTitle = (TextView)child;
            break;
        }
    }
    

提交回复
热议问题