Center Align title in action bar using styles in android.

前端 未结 4 610
再見小時候
再見小時候 2020-11-29 06:41

Hi I am developing android application. In my application I am using action bar. I want to make center align my title of window in action-bar. I know it is possible using xm

4条回答
  •  甜味超标
    2020-11-29 07:25

    Simple method to center ActionBarTitle without using custom layout for actionBar.

    But before that first hide up Icon as :

    myActionBar.setIcon(new ColorDrawable(Color.TRANSPARENT));
    
    private void centerActionBarTitle() {
        int titleId = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            titleId = getResources().getIdentifier("action_bar_title", "id", "android");
        } else {
            // This is the id is from your app's generated R class when 
            // ActionBarActivity is used for SupportActionBar
            titleId = R.id.action_bar_title;
        }
    
        // Final check for non-zero invalid id
        if (titleId > 0) {
            TextView titleTextView = (TextView) findViewById(titleId);
            DisplayMetrics metrics = getResources().getDisplayMetrics();
    
            // Fetch layout parameters of titleTextView 
            // (LinearLayout.LayoutParams : Info from HierarchyViewer)
            LinearLayout.LayoutParams txvPars = (LayoutParams) titleTextView.getLayoutParams();
            txvPars.gravity = Gravity.CENTER_HORIZONTAL;
            txvPars.width = metrics.widthPixels;
            titleTextView.setLayoutParams(txvPars);
            titleTextView.setGravity(Gravity.CENTER);
        }
    }
    

提交回复
热议问题