作者:奶油晓生2502876643 | 来源:互联网 | 2023-02-02 09:36
因此,正如您大多数人所知,Android中的TextView中没有文本可辩解。因此,我构建了一个自定义TextView来解决此问题。但是,由于某些原因,有时标点符号会在某些设备中由于某些原因而中断。我在LG G3和模拟器(运行最新版本的Nexus 4)和逗号“”上进行了测试,例如,它打破了LG G3而不是模拟器的理由。
如果我添加至少2的填充开始和结束(或左右),则此问题已解决。在我看来,这很武断。
基本上,我的逻辑是为了证明文本的正确性,我需要知道TextView本身的宽度,将文本构造成最大长度的行。然后,通过查找行中的空格数和剩余的空白空间,根据剩余的像素(或视图中的空格)拉伸要缩放的“”(空格)字符。
它几乎可以完美运行,并且在大多数情况下,它也支持RTL文本。
这是一些带有和不带有冒犯性标记的文本图片(一个简单的lorem插值)(第一张在运行7.1.1的模拟器nexus 4上,第二张在运行v5.0的LG G3上)
这是代码:
public class DTextView extends AppCompatTextView {
private boolean justify;
public DTextView(Context context) {
super(context);
}
public DTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void setJustify(boolean justify) {
this.justify = justify;
if (justify) {
justify();
}
}
private void init(@Nullable AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
justify = ta.getBoolean(R.styleable.DTextView_justify, false);
ta.recycle();
}
private SpannableStringBuilder justifyText() {
String[] words = getText().toString().split(" ");
setText("");
int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();
SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();
//This will build the new text with the lines rearranged so that they will have a width
//bigger than the View's own width
ArrayList lines = new ArrayList<>(0);
String line = "";
for (String word : words) {
if (getWordWidth(line + word)
我非常感谢任何可以对此有所启发的人。