Android xml布局:文本对齐
汉字在Android开发过程中为了美观效果,常常需要进行汉字对齐。如上图,为了两个汉字跟四个汉字一样对齐,一般的做法是直接用空格隔开。但是这样无法达到完美对齐的效果,因为一个空格的宽度≠一个汉字的宽度。1.xml布局中直接使用  (中文全角空格 (一个中文宽度))<TextViewandroid:layout_wi...
·
汉字

在Android开发过程中为了美观效果,常常需要进行汉字对齐。
如上图,为了两个汉字跟四个汉字一样对齐,一般的做法是直接用空格隔开。
但是这样无法达到完美对齐的效果,因为一个空格的宽度≠一个汉字的宽度。
1. xml布局中直接使用
  (中文全角空格 (一个中文宽度))
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="诊  断:"
android:textSize="14sp"
android:textColor="#ff424242" />
2. strings.xml中定义
\u3000(中文全角空格 (一个中文宽度))
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/chufang"
android:textSize="14sp"
android:textColor="#ff424242" />
<string name="chufang">处\u3000\u3000方</string>
英文小写

1. 直接空格
两个空格的宽度 = 一个英文小写的宽度
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ab d"
android:textColor="#ff424242"
android:textSize="14sp" />
2.xml布局直接使用
  (普通的英文半角空格但不换行)
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ab  d"
android:textColor="#ff424242"
android:textSize="14sp" />
3.strings.xml中定义
\u0020(半角空格(英文符号))
<string name="abcd">ab\u0020\u0020d</string>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/abcd"
android:textColor="#ff424242"
android:textSize="14sp" />
英文大写
未知。
后面知道了 再更新。
扩展
如果不嫌麻烦的话,可以使用android:visibility="invisible"占位。
这种方案能完美对齐各类文本,缺点就是太麻烦。
如代码就可以实现上面汉字对齐的效果:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="诊"
android:textColor="#ff424242"
android:textSize="14sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="占位"
android:textColor="#ff424242"
android:textSize="14sp"
android:visibility="invisible" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="断:"
android:textColor="#ff424242"
android:textSize="14sp" />
</LinearLayout>

参考
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)