我使用下面的代码来对齐操作栏标题中心。
try {
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 = (android.widget.LinearLayout.LayoutParams)titleTextView
.getLayoutParams();
txvPars.gravity = Gravity.CENTER_HORIZONTAL;
txvPars.width = metrics.widthPixels;
titleTextView.setLayoutParams(txvPars);
titleTextView.setSingleLine(false);
titleTextView.setMaxLines(2);
titleTextView.setPadding(5, 5, 5, 5);
titleTextView.setTextSize(17);
titleTextView.setGravity(Gravity.CENTER);
}
} catch (Exception e) {
Utility.printException(e);
}
此titleTextView
TextView返回null。
TextView titleTextView = (TextView) findViewById(titleId);
我正在使用ActionBarActivity。 app compact support library v7。
Theme.AppCompact.light
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="windowActionBar">false</item>
</style>
<style name="AppTheme" parent="AppBaseTheme">
<item name="actionOverflowMenuStyle">@style/OverflowMenu</item>
<!-- <item name="actionBarStyle">@style/Theme.MyApp.ActionBar</item> -->
</style>
<style name="OverflowMenu" parent="Widget.AppCompat.PopupMenu.Overflow">
<!-- Required for pre-Lollipop. -->
<item name="overlapAnchor">false</item>
<!-- Required for Lollipop. -->
<!-- <item name="android:overlapAnchor">false</item> -->
</style>