Getting ActionBar Title TextView with AppCompat v7 r21

前端 未结 5 947
长情又很酷
长情又很酷 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 04:55

    edit (september 2018): dont use it as of Android P reflection on android SDK may throw exception!

    I got it using reflection.

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Title"); //important step to set it otherwise getting null
    TextView title = null;
    try{
            Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
            f.setAccessible(true);
            title = (TextView) f.get(toolbar);
            title.setText("I have title TextView");
    } catch(Exception e){
            e.printStackTrace();
    }
    

    Please note that is works if I toolbar is not set to support ActionBar...

    setSupportActionBar(toolbar); // with this set text view behave differently 
                                  //and text may not be visible...
    

提交回复
热议问题