/
MyTextView.java
79 lines (67 loc) · 2.52 KB
/
MyTextView.java
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
package com.hudson.jetpackfeature.databinding.twoWayBind;
import android.content.Context;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.databinding.InverseBindingListener;
import androidx.databinding.InverseBindingMethod;
import androidx.databinding.InverseBindingMethods;
/**
* Created by Hudson on 2020/6/21.
*/
@InverseBindingMethods(@InverseBindingMethod(type = MyTextView.class,
event = "contentAttrChanged",//方法名必须是setContentAttrChanged
method = "getContent",//方法名必须是getContent
attribute = "content"))//方法名必须是setContent
public class MyTextView extends AppCompatTextView {
private InverseBindingListener mInverseBindingListener;
public MyTextView(Context context) {
this(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
if(mInverseBindingListener != null){
mInverseBindingListener.onChange();//通知数据类,当前视图内容变动了
}
}
public void setContent(String content){
String current = getText().toString();
if(content != null && !content.equals(current)){
setText(content);
}
}
public String getContent(){
return getText().toString();
}
public void setContentAttrChanged(InverseBindingListener listener){
if(listener != null){
mInverseBindingListener = listener;
}else{
mInverseBindingListener = null;
}
}
// //用于数据变动刷新到视图view
// @BindingAdapter({"content"})
// public static void setContent(MyTextView view,String content){
// String current = view.getText().toString();
// if(content != null && !content.equals(current)){//避免进入死循环
// view.setText(content);
// }
// }
//
// @InverseBindingAdapter(attribute = "content",event = "contentAttrChanged")
// public static String getContent(MyTextView view){
// return view.getText().toString();
// }
//
// @BindingAdapter(value = {"contentAttrChanged"},requireAll = false)
// public static void setContentChanged(MyTextView view, InverseBindingListener listener){
// view.mInverseBindingListener = listener;
// }
}