Android水平居中放置TextView,同时保持左对齐 [英] Android center TextView horizontally while keeping left align
本文介绍了Android水平居中放置TextView,同时保持左对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如我的标题所述,我希望TextView中的文本在其父元素中水平居中,同时保持文本对齐:
As my title describes, I want the text in a TextView to be horizontally centered in it's parent element while keeping the text left aligned:
所以这:> p>
So this:
| Text |
| TextText |
变为:
| Text |
| TextText |
Android可能吗?
Is this possible with Android?
这是我当前的布局:
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.25"
android:background="@drawable/table_cell"
android:gravity="center"
android:text="@string/table_last_training" />
在此先感谢
McFarlane
Thanks in advance, McFarlane
推荐答案
private String hackSpace(Context context, float textSize, String text) {
TextView textView = new TextView(context);
textView.setTextSize(textSize);
ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
textView.setLayoutParams(textViewParams);
String[] sentences = text.split("\n");
//calculate space width
textView.setText(" ");
textView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int slice = textView.getMeasuredWidth();
//calculate each sentence
int[] sentencesWidth = new int[sentences.length];
//store max width
int maxWidth = 0;
for (int i = 0; i < sentences.length; i++) {
textView.setText(sentences[i]);
textView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
sentencesWidth[i] = textView.getMeasuredWidth();
if (sentencesWidth[i] > maxWidth) {
maxWidth = sentencesWidth[i];
}
}
//add space after each sentence if necessary
for (int i = 0; i < sentences.length; i++) {
int spaceNum = (maxWidth - sentencesWidth[i]) / slice;
StringBuilder sb = new StringBuilder();
for (int k = 0; k < spaceNum; k++) {
sb.append(" ");
}
sentences[i] += sb.toString();
}
//rebuild String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sentences.length; i++) {
sb.append(sentences[i]);
if (i != sentences.length - 1) {
sb.append("\n");
}
}
return sb.toString();
}
这篇关于Android水平居中放置TextView,同时保持左对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文