Java 在android中对齐中心菜单项文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19344297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Align Center Menu Item text in android
提问by Muhammad Umar
Using following code
使用以下代码
<item
android:id="@+id/text"
android:title="@string/mainMenu"
android:enabled="false"
android:layout_gravity="center">
</item>
I have a style defined as
我的风格定义为
<style name="MenuTextStyle" parent="@android:style/TextAppearance.Medium">
<item name="android:textColor">6F6B6B</item>
<item name="android:gravity">center_horizontal</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">14sp</item>
But the menu text still is not in the middle. How to make it center in middle?
但是菜单文本仍然不在中间。如何使它居中?
回答by Mahm00d
You can center-align the menu items dynamically using SpannableString
in your activity:
您可以SpannableString
在您的活动中使用动态居中对齐菜单项:
int positionOfMenuItem = 0; //or any other postion
MenuItem item = menu.getItem(positionOfMenuItem);
SpannableString s = new SpannableString(settingsItemTitle);
s.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_CENTER), 0, s.length(), 0);
item.setTitle(s);
回答by turbandroid
Another way to achieve this is via setting theme
实现此目的的另一种方法是通过设置主题
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:theme="@style/ThemeToolbar.NavigationViewPadding"
app:itemTextColor="@color/inverse_color"
app:itemIconTint="@color/inverse_color"
app:itemBackground="@drawable/selector_navigation"
app:headerLayout="@layout/activity_home_nav_header"
app:menu="@menu/activity_home_drawer" />
In your styles
在你的风格
<style name="ThemeToolbar.NavigationViewPadding">
<item name="listPreferredItemPaddingLeft">50dp</item>
</style>
回答by u7538854
I used @Mahm00d's way, that worked perfectly, but I found another way to solve the problem. It is to add \t
before the String. If the space isn't enough, I can add more.
我使用了@Mahm00d 的方法,效果很好,但我找到了另一种解决问题的方法。它是\t
在String之前添加的。如果空间不够,我可以添加更多。
Because Chinese words are one by one, the length of the item is same.
因为中文单词是一个一个的,所以项目的长度是一样的。