gpt4 book ai didi

java - 具有 inter_word justificationMode 的可选 TextView

转载 作者:行者123 更新时间:2023-12-01 19:33:37 24 4
gpt4 key购买 nike

我正在尝试使用 justificationMode 使可选择的 TextView 对齐。看来这两个属性不能共存,因为当我从 TextView 中删除 android:textIsSelectable="true" 时,它就变得合理了。这是 TextView :

    <TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/sf_reg"
android:padding="16dp"
android:textIsSelectable="true"
android:justificationMode="inter_word"
android:gravity="left|top"
android:textColor="@android:color/black"
android:textSize="15sp" />

我使用的是 androidx.appcompat:appcompat:1.1.0,targetSdkVersion 为 29,minSdkVersion 为 26。

最佳答案

自 Oreo 以来,Android 仅支持 Textview 上的完全对齐,尽管我们很难使用 justificationMode 对 textview 进行对齐。但是您可以通过在类中编写一个简单的方法来实现合理化。

public void Justify(final TextView textView) {

final AtomicBoolean isJustify = new AtomicBoolean(false);

final String textString = textView.getText().toString();

final TextPaint textPaint = textView.getPaint();

final SpannableStringBuilder builder = new SpannableStringBuilder();

textView.post(new Runnable() {
@Override
public void run() {

if (!isJustify.get()) {

final int lineCount = textView.getLineCount();
final int textViewWidth = textView.getWidth();

for (int i = 0; i < lineCount; i++) {

int lineStart = textView.getLayout().getLineStart(i);
int lineEnd = textView.getLayout().getLineEnd(i);

String lineString = textString.substring(lineStart, lineEnd);

if (i == lineCount - 1) {
builder.append(new SpannableString(lineString));
break;
}

String trimSpaceText = lineString.trim();
String removeSpaceText = lineString.replaceAll(" ", "");

float removeSpaceWidth = textPaint.measureText(removeSpaceText);
float spaceCount = trimSpaceText.length() - removeSpaceText.length();

float eachSpaceWidth = (textViewWidth - removeSpaceWidth) / spaceCount;

SpannableString spannableString = new SpannableString(lineString);
for (int j = 0; j < trimSpaceText.length(); j++) {
char c = trimSpaceText.charAt(j);
if (c == ' ') {
Drawable drawable = new ColorDrawable(0x00ffffff);
drawable.setBounds(0, 0, (int) eachSpaceWidth, 0);
ImageSpan span = new ImageSpan(drawable);
spannableString.setSpan(span, j, j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}

builder.append(spannableString);
}

textView.setText(builder);
isJustify.set(true);
}
}
});
}

然后将您的 TextView 传递到方法内,

Textview tv = findviewbyid(R.id.text);
Justify(tv);

最棒的是,它不仅限于 Oreo,它还可以在其他较低版本的 Android 上运行。

android:textIsSelectable="true"

使用此方法文本选择也可以正常工作。

关于java - 具有 inter_word justificationMode 的可选 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58600246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com