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();
}
您可能需要創建一個自定義的視圖類和處理中的onDraw TextView的繪圖參數,據一個我知道它正在改變根據屏幕的這樣做,因爲你將不得不處理的唯一途徑/佈局尺寸僅在onMeasure之後確定。這是除非你真的想一起破解它,在這種情況下,你可以創建一個方法,根據需要添加空格作爲填充。如果你願意,我可以回答你如何做黑客攻擊(儘管我不會推薦它):P)。也有幾種方法可以使用純XML來做到這一點,但我發現它變得混亂。 – zgc7009