小编Sha*_*ayR的帖子

在Android中的TextView中对齐文本

因此,正如您大多数人所知,Android中的TextView中没有文本可辩解。因此,我构建了一个自定义TextView来解决此问题。但是,由于某些原因,有时标点符号会在某些设备中由于某些原因而中断。我在LG G3和模拟器(运行最新版本的Nexus 4)和逗号“”上进行了测试,例如,它打破了LG G3而不是模拟器的理由。

如果我添加至少2的填充开始和结束(或左右),则此问题已解决。在我看来,这很武断。

基本上,我的逻辑是为了证明文本的正确性,我需要知道TextView本身的宽度,将文本构造成最大长度的行。然后,通过查找行中的空格数和剩余的空白空间,根据剩余的像素(或视图中的空格)拉伸要缩放的“”(空格)字符。

它几乎可以完美运行,并且在大多数情况下,它也支持RTL文本。

这是一些带有和不带有冒犯性标记的文本图片(一个简单的lorem插值)(第一张在运行7.1.1的模拟器nexus 4上,第二张在运行v5.0的LG G3上) 在模拟器上运行nexus 4上运行的文本 在运行Android 5.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 = …
Run Code Online (Sandbox Code Playgroud)

android textview android-custom-view spannablestring

5
推荐指数
1
解决办法
8870
查看次数