Android DataBinding advanced usage

DataBinding get started quickly, layout details:
1. There can be multiple import tags in the <data>...</data> tag. You can import references in the layout file just like using Java.

2. When the class name conflicts, you can use alias, like this:

< data>

<import type=“com.wenzhibin.View”

alias = "myView" />

< /data>

3. There can be any number of variable tags in the <data>...</data> tag. Each variable tag describes the attributes that will be used in the binding expression. The name value in each variable tag is a variable in the binding class.

4. The automatically generated binding class generates getter/setter functions for each variable. These variables will use Java's default assignment until the setter function is called. The default assignments are null, 0 (int), false (boolean), etc. The following example:

In XML,

< data>

< import type=“android.graphics.drawable.Drawable”/>

< variable name=“studentModel” type=“com.wenzhibin.StudentModel”/>

< variable name=“image” type=“Drawable”/>

< variable name=“note” type=“String”/>

< /data>

The corresponding getter setter is generated in the automatically generated binding class,

public abstract com.wenzhibin.StudentModel.getStudentModel();

public abstract void setStudentModel(com.wenzhibin.StudentModel studentModel);

public abstract Drawable getImage();

public abstract void setImage(Drawable image);

public abstract String getNote();

public abstract void setNote(String note);

5. When writing different layout files for different configurations (such as horizontal and vertical screen layouts), variables will be merged. Therefore, there can be no conflicts between these layout files of different configurations.

6. Import can also be used to use static methods in expressions,

E.g:

public class StringUtils{

public static Stringnew(final String word){

if(word.length() >5) {

return word+"I am learning advanced usage of DataBinding";

}

return word;

}

}

< data>
< import type=“com.wenzhibin.utils.StringUtils” />
< variable name=“studentModel” type=“com.wenzhibin.StudentModel”/>

< /data>

<TextView

android:text="@{StringUtils.Stringnew(studentModel.name)}"

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

7. The classes in the java.lang.* package will be automatically imported and can be used directly. For example, to define a String type variable:

**

Advanced usage of DataBinding:

**
**

1. List binding

**

RecyclerView data binding open source library:

evant / binding-collection-adapter

radzio / android-data-binding-recyclerview

If you feel that these two libraries are not flexible enough, you can package them yourself.

2. Custom attributes

When binding, the setXXX method will be called. If the view provides the attribute method, it can be set through DataBinding. For example, TextView itself has a built-in setText(String text) method, and we only need android:text="@{studentModel.name }", DataBinding will automatically look for the set method------>setText(studentModel.namet) and go up. Assuming that TextView does not have a setText(String text) method, then a custom attribute is required. There are two ways of writing:

a) If there are similar methods with different method names, you can call the existing method by setting the BindingMethod.

For example, android:onClick, there is no setOnClick method in View, but there is a setOnClickListener method,

At this time we can use BindingMethod (also known as Binding method) to do a mapping. When you see "android:onClick" using DataBinding in the xml file, setOnClick will be mapped to setOnClickListener

@BindingMethods({

@BindingMethod(

type=View.class,

attribute=“android:onClick”,

method=“setOnClickListener”)

})

@BindingMethods is defined above the class name. ( ps : Just add the above code in front of a certain class, this comment will be checked before compilation, and then automatically called as a Binding method)

Of course, if you just want to rename the setter method, you can also use @BindingMethods.

b). If there is no similar method, you can add the corresponding method by setting the BindingAdapter.

For example, in android:paddingRighttts, there is no setPaddingpaddingRighttts method in View, only the setPadding method.

At this time, you can customize a set method and add @BindingAdapter (also known as Binding Adapter) to the method.

//Single attribute

@BindingAdapter(“android:paddingRighttts”)

public static void setPaddingRightRighttts(View view, int padding){

view.setPadding( view.getPaddingLeft(), view.getPaddingTop() ,padding, view.getPaddingBottom());

}

//Multi-attribute adaptation, the same method can set multiple attributes at the same time

public class MyBindingAdapter {

@BindingAdapter({“imageUrl”,“placeholder”})

public static void loadImageFromUrl(ImageView view,String url,Drawable drawable) {

Glide.with(view.getContext()).load(url).placeholder(drawable).into(view);

}

}

Used in xml, (the Binding adapter of the MyBindingAdapter class will be automatically called)

< data>
< import type=“android.graphics.drawable.Drawable”/>
< variable name=“studentModel” type=“com.wenzhibin.StudentModel”/>

< /data>

<ImageView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android: scaleType = "fitXY"

app:imageUrl="@{studentModel.headUri}"

app:placeholder="@{@drawable/default_headimg}"/>

(**ps:** If you write @BindingAdapter({"xxx"}) like this or @BindingAdapter({"bind:xxx"}) like this, write app:xxx="@{... }"; If you write @BindingAdapter({"android:xxx"}) like this, write android:xxx="@{…}") when xml layout refers to attributes

**

3. BindingConversion conversion to setter properties

**

<View

android:background= “@(isError ? @color/red : @color/white}”

android:layout_width= “wrap_content”

android:layout_height= “wrap_content” />

@BindingConversion

public static ColorDrawable convertColorToDrawable(int color) { return new ColorDrawable(color);}

In the code example, the background property of View needs Drawable, but we assign color to it, and the color can be converted to Drawable through @BindingConversion, and then color can be used as the background background.

4. Two-way binding

On the one hand, changes in the Model will affect the display of the UI interface; on the other hand, changes in the UI interface will also affect the update of the corresponding fields in the Model. Simply speaking, they affect each other, which is two-way binding. Using "@=" in XML can easily achieve two-way binding. such as:

Sample code in XML:

< data>

<variable

name=“studentModel”

type=“com.wenzhibin.StudentModel”/>

< /data>

<EditText

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:inputType=“textNoSuggestions”

android:text="@={studentModel.name}"/>

<Button

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:text="@{studentModel.name}"/>

When the user enters, the text above will change, and the text will be directly assigned to the name attribute of the StudentModel. At this time, the text of the Button and the text of the Button display the same content, because the StudentModel has been updated. We can also monitor property changes, as shown in the following example in java code:

studentModel.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
@Override

public void onPropertyChanged(Observable observable,int i) {

……

do something
……

}

5. Expression chain

Repeated expressions in XML:

< data>

< import type=“android.view.View”/>

< /data>

< ImageView android:visibility= “@{studentModel.isGraduate ? View.VISIBLE : View.GONE}” />

< TextView android:visibility= “@{studentModel.isGraduate ? View.VISIBLE : View.GONE}” />

< CheckBox android:visibility= “@{studentModel.isGraduate ? View.VISIBLE : View.GONE}” />

Through the simplified expression:

< data>

< import type=“android.view.View”/>

< /data>

<ImageView

android:id= “@+id/img_head”

android:visibility= “@{studentModel.isGraduate ? View.VISIBLE : View.GONE}” />

< TextView android:visibility= “@{img_head.visibility}” />

< CheckBox android:visibility="@{img_head.visibility}"/>

Implicit update

< data>

< import type=“android.view.View”/>

< /data>

< CheckBox android:id= “@+id/isRemember” />

< ImageView android:visibility= “@{isRemember.checked? View.VISIBLE : View.GONE}” />

As can be seen from the above example, we do not need to go to the Java code to determine whether the CheckBox is selected to control the display and hiding of the picture.

6.lambda expression

a) Alternatives to method references

android:onClick ="@ {(view)-> presenter.onUserClick(view,user)}”

b) Omit parameters, or declare all parameters (usually no view is needed)

android:onClick ="@ {()-> presenter.onUserClick(user)}"

android:onFocusChange =“@{(v,fcs)-> presenter.onFocusChangelistner(user)}"

c) Expressions and reference variables can be used in Lambda

d) Special variables: view id (pass the camel case variable name of another View), including context variables

Sample code:

In the LambdaDemoActivity class
public class LambdaDemoActivity extends AppCompatActivity {

private ActivityLambdaDemoBinding myBinding;

public class Presenter {

onUserClick(User user) {

Toast.makeText(LambdaDemoActivity.this,“onUserClick”,

Toast.LENGTH_SHORT).show();

}

public void onUserLongClick(User user, Context mContext) {

Toast.makeText(mContext,“onUserLongClick”,

Toast.LENGTH_SHORT).show();

}

public void onFocusChangelistner(User user) {

Toast.makeText(LambdaDemoActivity.this,“onFocusChangelistner”,

Toast.LENGTH_SHORT).show();

}

}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myBinding = DataBindingUtil.setContentView(this, R.layout.activity_lambda_demo);
myBinding.setUser(new User(“wenzhibin”,“123456”));
myBinding.setPresenter(new Presenter());

}

}

In activity_lambda_demo.xml

< data>

< variable name=“presenter” type=“com.wenzhibin.LambdaDemoActivity.Presenter”/>

< variable name=“user” type=“com.wenzhibin.User”/>

< /data>

<Button android:onClick ="@ {()-> presenter.onUserClick(user)}"/>

(**ps:** The following line of code declares all the parameters. The two parameter names can be written freely, not v, fcs, as long as the two parameter names are different. Even omit all parameters, the following two v, fcs It’s
okay not to write the parameter.) <Button android: onFocusChange = "@{(v,fcs)-> presenter.onFocusChangelistner(user)}"/>

<Button
android:text="@{user.loginName}"

(**ps:**In the XML layout, we did not define the context variable. The databinding helped us get the context, that is, the activity)
android:onClick="@{(v) -> presenter.onUserLongClick( user, context)

}/>

7. Animation

The databinding has encapsulated the animation, we only need to call the following code:

myBinding.addOnRebindCallback(new OnRebindCallback() {

@SuppressLint(“NewApi”)
@Override
public boolean onPreBind(ViewDataBinding binding) {

ViewGroup view = (ViewGroup) binding.getRoot();

TransitionManager.beginDelayedTransition(view);

return true;

}

});

Guess you like

Origin blog.csdn.net/yanhuomatou2015/article/details/108840947