The use and detailed explanation of (layout) events, operation logic, resources, and tools in the layout of Android DataBinding (7)

1. Introduction

        If you have studied my previous six articles, you can basically handle most of the business of data binding in the development process. However, since the data in the layout does not necessarily meet the effect on the UI, it is normal to process the data in advance. If we In the introduction of layout, events, operation logic, resources, tools? Then the code layer will appear very natural and clean.

        After understanding that layout can introduce these, we should look forward to how these classes are used in the layout of the layout?

2. Detailed explanation

1. Operator logic usage

The following operators, expressions and keywords are supported in layout files

  • Arithmetic + - / * %
  • string merge +
  • Logical && || (& in xml expression is: &)
  • Binary & | ^ (& expressed in xml is: &)
  • Unary + - ! ~
  • Shift >>> >>> <<
  • compare == > < >= <=
  • instanceof
  • Grouping ()
  • character, String, numeric, null
  • Cast
  • method call
  • Field access
  • Array access[]
  • Ternary?:

The following operations are not currently supported

  • this
  • super
  • new
  • Show generic calls

escape character:

character escape character
> &gt;
< &lt;
& &amp;
" &quot;

data:

<data class="MyDataBindDetail">

    <import type="android.text.TextUtils" />

    <variable
        name="data1"
        type="String" />

    <variable
        name="data2"
        type="String" />

    <variable
        name="data3"
        type="String" />


    <variable
        name="value"
        type="int" />

</data>

But it is impossible for us to use it completely. Let me list some of them from a commonly used perspective.

arithmetic

+:android:text="@{String.valueOf(1+2)}"

-:android:text="@{String.valueOf(200-2)}"

/:android:text="@{String.valueOf(10/2)}"

*:android:text="@{String.valueOf((2*2))}"

%:android:text="@{String.valueOf(7%3)}"

Character concatenation:

+:android:text="@{ data1+data2+data3}"

In fact, Impl will generate the corresponding logic:

 && operation:

android:text="@{String.valueOf(value&gt;2 &amp;&amp; value&lt;6) }"

||运算:
android:text="@{String.valueOf(value&gt;2 || value&lt;6) }"

instanceof type judgment:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{data3+ &quot;   instanceof= &quot;}" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{data3 instanceof String ? &quot; String &quot; : &quot; notString &quot;}" />

Trinocular operation?: 

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{value> 2? " greater than " : " less than or equal to "}" />

2. Resource usage

Resources currently support string and dimens

string: only formate is supported, or a single import,

<string name="txt1">你好%s%s%s</string>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{@string/txt1(data1,data2,data3)}" />

String needs to specify the correct placeholder (content type), {0} cannot be used, which is different from Message.format

dimen:

Support logical operations

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{@string/txt1(data1,data2,data3)}"
    android:textSize="@{flag?@dimen/app_bar_height:@dimen/fab_margin}"
    />

3. Static class usage

        In the layout, we can complete the logic modification through the static class. This will be more convenient. But in a static class, layout files cannot use static modules in the class.

object MyUtil {


        fun text(txt: String): String {

            if (txt.equals("zhang")) {
                return "这不是老张嘛"
            }
            return "大家都是老王"
        }

        fun text(age: Int): String {


            return "老王今年${age}岁"
        }

}

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data class="ClassMethodUtil">

        <import type="com.example.wiik.testdemo.databinding.util.MyUtil" />

        <variable
            name="name"
            type="String" />

        <variable
            name="age"
            type="int" />


    </data>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{MyUtil.INSTANCE.text(name)}" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{MyUtil.INSTANCE.text(age)}" />

    </LinearLayout>


</layout>

        Static addition can simplify complex logic calculations in xml. If you can't use the logic in the layout, you can't remember the escape characters and you can handle it through static classes.

Notice:

Classes in layouts must not reference methods in static modules. mistake

class MyUtil {


   
   companion object{

        fun text(txt: String): String {

            if (txt.equals("zhang")) {
                return "这不是老张嘛"
            }
            return "大家都是老王"
        }

        fun text(age: Int): String {


            return "老王今年${age}岁"
        }

       
   } 
    
}

4. Class method calls

        The method of the class is similar to that of the static class, one is initialized and the other is used directly. But if some people like to extract some logic in an M layer when using MVVM, they can also use it in the same way.

, the inner class of M layer:

    inner class MyMethodEntity(var context:Context){



        fun  getName(resId:Int):String{
            return context.getString(resId)
        }

        fun getSizeName(name:String):String{
            return "${name}长度为=${name.length}"
        }
    }

The layout is handled as follows:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data class="ClassMethodUtil">


        <import type="com.example.wiik.testdemo.databinding.TestMethodActivity.MyMethodEntity" />

        <variable
            name="name"
            type="String" />

        <variable
            name="age"
            type="int" />

        <variable
            name="entity"
            type="MyMethodEntity" />

        <variable
            name="resId"
            type="int" />

    </data>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{entity.getName(resId)}" />


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{entity.getSizeName(name)}" />

 

    </LinearLayout>


</layout>

This is also handled with the help of methods provided by the class.

5. Event binding

        In android, an event is the occurrence of an action, especially View, which provides the capture of various events, captures them through screen sensing and then processes them, passes them to the bottom layer, and processes them into corresponding events.

  • android:onClick
  • android:onLongClick

The binding of events can be done without using set in the code, but the binding should also be done according to the original event method.

For example:

android:onClick



object MyUtil {



    fun onClick(view: View) {
        Toast.makeText(view.context, "我点击l ", Toast.LENGTH_SHORT).show()
    }



}

Introduced in the xml layout:

      <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{MyUtil.INSTANCE.onClick}"
            android:text="点击onClick" />

explain:

If the parameter is only the current object, it can be directly referenced without passing

If there is a return value:

    fun onLongClick(view: View): Boolean {
        Toast.makeText(view.context, "我点击2 ", Toast.LENGTH_SHORT).show()
        return false
    }
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onLongClick="@{MyUtil.INSTANCE.onLongClick}"
            android:text="onLongClick" />

Native:

public interface OnLongClickListener {

    boolean onLongClick(View v);
}
public interface OnClickListener {

    void onClick(View v);
}

Notice:

        Custom events, parameters and return values ​​must match the system, otherwise an error will be reported.

        Custom events can be in the inner class of M layer, or in any class, as long as the method is responsible for the custom class, it can be used

6、Null Coalescing

? ? : If the first parameter is not null, it will take the first one, otherwise it will take the second value.

     <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{name??entity.getName(resId)}"

            />

3. Two-way binding feature

        The platform provides built-in support for two-way data binding when you use the features in the table below. See the implementation of the appropriate binding adapter for details on how the platform provides such support:        

kind characteristic binding adapter
AdapterView android:selectedItemPosition
android:selection
AdapterViewBindingAdapter
CalendarView android:date CalendarViewBindingAdapter
CompoundButton android:checked CompoundButtonBindingAdapter
Date Picker android:year
android:month
android:day
DatePickerBindingAdapter
NumberPicker android:value NumberPickerBindingAdapter
RadioButton android:checkedButton RadioGroupBindingAdapter
RatingBar android:rating RatingBarBindingAdapter
SeekBar android:progress SeekBarBindingAdapter
TabHost android:currentTab TabHostBindingAdapter
TextView android:text TextViewBindingAdapter
TimePicker android:hour
android:minute
TimePickerBindingAdapter

Four. Summary

        Through the above introduction, we can master the use of logic, events, and tool classes in layout. This way we can easily handle some things in the layout.

Guess you like

Origin blog.csdn.net/qq36246172/article/details/128237844