Android中ActionBar居中

经常会用到将ActionBar文字居中的问题,这里写个代码如下:

    //把actionBar的文字标题居中
    public static void centerActionBarTitle(Activity activity)
    {
        int titleId = activity.getResources().getIdentifier("action_bar_title", "id", "android");
        if (titleId<=0)return;
        TextView titleTextView = (TextView)activity.findViewById(titleId);
        DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
        LinearLayout.LayoutParams txvPars = (LinearLayout.LayoutParams) titleTextView.getLayoutParams();
        txvPars.gravity = Gravity.CENTER_HORIZONTAL;
        txvPars.width = metrics.widthPixels;
        titleTextView.setLayoutParams(txvPars);
        titleTextView.setGravity(Gravity.CENTER);
}


你可能感兴趣的:(Android常见问题)