androidandroid-actionbarandroid-titlebar

Center Action bar title


How can I center activity's action bar title in Android?

I've seen MANY questions on SO for this specific topic. And every answer comes back to "using custom view" and having your own toolbar.

I've found a solution that works without creating a custom view.


Solution

  • Have this method in your Activity:

    private void centerTitle() {
        ArrayList<View> textViews = new ArrayList<>();
    
        getWindow().getDecorView().findViewsWithText(textViews, getTitle(), View.FIND_VIEWS_WITH_TEXT);
    
        if(textViews.size() > 0) {
            AppCompatTextView appCompatTextView = null;
            if(textViews.size() == 1) {
                appCompatTextView = (AppCompatTextView) textViews.get(0);
            } else {
                for(View v : textViews) {
                    if(v.getParent() instanceof Toolbar) {
                        appCompatTextView = (AppCompatTextView) v;
                        break;
                    }
                }
            }
    
            if(appCompatTextView != null) {
                ViewGroup.LayoutParams params = appCompatTextView.getLayoutParams();
                params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                appCompatTextView.setLayoutParams(params);
                appCompatTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            }
        }
    }
    

    Then, just call it in your onCreate():

    centerTitle();
    

    That's it!!!