基于Android DataBinding的BindingAdapter实现密码字符*的回显
作为BindingAdapter使用的简单小练习,记下。本例实现一个简单功能:当在EditText里面输入一个任意字符时候,在下方的TextView实时回显*号。
写一个User数据模型:
package zhangphil.test;
import android.databinding.BaseObservable;
import android.databinding.ObservableField;
/**
* Created by Phil on 2017/8/17.
*/
public class User extends BaseObservable {
public final ObservableField<String> content = new ObservableField<>();
}
写一个activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="zhangphil.test.Util" />
<variable
name="user"
type="zhangphil.test.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="@={user.content}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:password="@{user.content}" />
</LinearLayout>
</layout>
MainActivity.java:
package zhangphil.test;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import zhangphil.test.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user = new User();
binding.setUser(user);
}
}
任意写一个Util.java:
package zhangphil.test;
import android.databinding.BindingAdapter;
import android.util.Log;
import android.widget.TextView;
/**
* Created by Phil on 2017/8/18.
*/
public class Util {
@BindingAdapter(value = {"password"})
public static void setTxt(TextView view, CharSequence text) {
if (text == null) {
Log.d("BindingAdapter setText", "为空");
return;
}
String s = "";
for (int i = 0; i < text.length(); i++) {
s = s + "*";
}
view.setText(s);
}
}
注意这里面的定义和特性。BindingAdapter的注解符会将在xml定义的:
app:password
与Util.java中定义的setText方法绑定,而setTxt由password触发。然后显示密码符号*。
代码运行结果: