Linjiajia
2023-07-25 82e57df230ecb744af6c8865f80870ba03c86d89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.android.app_base.base.adapter.databinding;
 
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
import androidx.databinding.BindingAdapter;
import androidx.databinding.InverseBindingAdapter;
 
import java.math.BigDecimal;
import java.util.Locale;
 
/**
 * @author Ljj
 * @date 2023.05.22. 21:10
 * @desc
 */
public class TextViewAdapter {
    /**
     * 设置TextView的Ellipsize
     *
     * @param textView TextView
     * @param ellipsize 1:开头 2:中间 3:结尾 4:跑马灯 0或其他:不设置
     */
    @BindingAdapter({"textOverflowMode"})
    public static void setTextViewEllipsize(TextView textView, int ellipsize) {
        TextUtils.TruncateAt where = null;
        switch (ellipsize){
            case 1:
                where = TextUtils.TruncateAt.START;
                break;
            case 2:
                where = TextUtils.TruncateAt.MIDDLE;
                break;
            case 3:
                where = TextUtils.TruncateAt.END;
                break;
            case 4:
                where = TextUtils.TruncateAt.MARQUEE;
                break;
            default:
                break;
        }
        if (textView.getEllipsize() == where) {
            return;
        }
        textView.setEllipsize(where);
        if (where != TextUtils.TruncateAt.MARQUEE) {
            return;
        }
        if (!textView.isSelected()) {
            // 设置跑马灯之后需要设置选中才能有效果
            textView.setSelected(true);
        }
        if (!textView.isFocusable()) {
            // 设置跑马灯需要先获取焦点
            textView.setFocusable(true);
        }
        textView.setSingleLine(true);
        // 设置跑马灯的循环次数
        textView.setMarqueeRepeatLimit(-1);
    }
 
    @BindingAdapter("android:text")
    public static void setText(TextView view, double value) {
//        String formattedValue = String.format(Locale.CHINA, "%.2f", value);
//        if (!TextUtils.equals(view.getText().toString(), formattedValue)) {
//            view.setText(formattedValue);
//        }
        view.setText(BigDecimal.valueOf(value).stripTrailingZeros().toPlainString());
    }
 
    @InverseBindingAdapter(attribute = "android:text")
    public static double getText(TextView view) {
        String text = view.getText().toString();
        if (TextUtils.isEmpty(text)) {
            return 0.0;
        } else {
            return Double.parseDouble(text);
        }
    }
 
}