Jetpack---DataBinding

這幾年一定會(huì)火起來(lái)的一個(gè)架構(gòu)
以前說(shuō)了MVP---V---P---M他們之間的關(guān)系

那么MVVP他也相當(dāng)于一個(gè)三層結(jié)構(gòu)View--ViewModle--Modle,他的一個(gè)好處是可以雙向綁定,在View和Modle之間,他有一個(gè)databinding,可以把View和Model進(jìn)行綁定,說(shuō)法也可以叫雙向綁定。寫頁(yè)面多的APP用這種會(huì)很方便,當(dāng)model數(shù)據(jù)發(fā)生變化的時(shí)候,view也能實(shí)時(shí)發(fā)生變化。他的開發(fā)速度非??欤揖S護(hù)起來(lái)也很簡(jiǎn)單。Model層都不怎么需要我們關(guān)系,我們把時(shí)間精力放在view和viewmodel上面就可以了,時(shí)間精力更多的放在UI設(shè)計(jì)這一塊。

一 簡(jiǎn)單使用

寫一個(gè)很簡(jiǎn)單的demo,類似一個(gè)登陸界面,輸入賬號(hào)密碼的
注意要在配置文件配置這句話

image.png
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <data>
        <!--此處定義該布局要用到的數(shù)據(jù)的名字和類型-->
        <variable
            name="user"
            type="com.example.lsn42_mvvm_20191009.User" />
    </data>
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        
        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            app:header="@{user.header}"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`姓名:`+user.name}"
             />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`密碼:`+user.password}"
            />
    </LinearLayout>
</layout>

根目錄一定要是layout,data標(biāo)簽配合variable這里表示該布局定義的數(shù)據(jù)名稱和類型,這個(gè)類型就是Userbean
app:header="@{user.header}表示自定義屬性,user.name user.password就不多說(shuō)了

/**
 * 這個(gè)類就相當(dāng)于一個(gè)ViewModel
 */
public class User extends BaseObservable {
    private String name;
    private String password;

    private String header;

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public User(String name, String password,String header) {
        this.name = name;
        this.password = password;
        this.header=header;
    }

    @Bindable
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);

    }
    @Bindable
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
        notifyPropertyChanged(BR.password);
    }
    //自定義屬性:提供一個(gè)靜態(tài)方法來(lái)加載image
    @BindingAdapter("bind:header")
    public static void getImage(ImageView view,String url){
        Picasso.with(view.getContext()).load(url).into(view);
    }
}

既然寫一個(gè)登陸頁(yè)面賬號(hào)密碼的demo,那么name和password就對(duì)應(yīng)著賬號(hào)密碼,header這里表示自定義屬性。我們都進(jìn)行g(shù)et和set方法
注意了:這里我們要在賬號(hào)密碼的get方法上面添加@Bindable注解。在set方法里面添加notifyPropertyChanged(BR.name)

至于我們之前在布局里里寫的imageview,我們自定義了一個(gè)header屬性,我們?cè)賮?lái)寫一個(gè)方法,方法是靜態(tài)方法并且里面一定要聲明@BindingAdapter("bind:header")這里bind:header就相當(dāng)于已經(jīng)把布局里面的imageview綁定再一起了,然后調(diào)用picasso加載就行了。

至于在Activity我們的表示是。

public class MainActivity extends AppCompatActivity {

    User user;

    Handler handler=new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        ActivityMainBinding binding=DataBindingUtil.setContentView(this,R.layout.activity_main);
        //這些數(shù)據(jù)是model層來(lái)的
        user=new User("dasuda","123","http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg");
        binding.setUser(user);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                user.setName("alan");
                user.setPassword("*******");
            }
        },5000);
    }
}

有兩個(gè)地方需要注意:
我們這時(shí)候setcontentView就不能用以前的,要用ActivityMainBinding binding=DataBindingUtil.setContentView(this,R.layout.activity_main)拿到綁定布局。

然后我們?cè)煲粋€(gè)數(shù)據(jù)源User,最后一步去綁定數(shù)據(jù)源binding.setUser(user);
這里我們模擬了一開始啟動(dòng)的時(shí)候,會(huì)看到一個(gè)我們初始值的賬號(hào)密碼,后面我用handler延遲5秒消息去改變這個(gè)賬號(hào)密碼,那么對(duì)應(yīng)的UI界面就會(huì)5s去改變這個(gè)賬號(hào)密碼。

如果要點(diǎn)擊事件的話,我們可以加上@{user.click},并且在User類里面處理

<TextView
            android:onClick="@{user.click}"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@{user.password}"/>
 public void click(View view){
        Toast.makeText(view.getContext(),getName() , Toast.LENGTH_SHORT).show();
    }
如果布局當(dāng)中有l(wèi)istview或者RecycleView這種怎么寫?

我們的MainActivity里面直接放入listview。activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  >

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

User類里面寫法還是和之前一樣的,User就對(duì)應(yīng)每個(gè)item的條目,因此此處的item的布局寫法也是和上面一樣的。item.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>
        <variable
            name="user"
            type="com.example.lsn42_mvvm_2019100902.User"/>
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ImageView
            app:header="@{user.header}"
            android:layout_width="50dp"
            android:layout_height="50dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@{user.name}"/>
        <TextView
            android:onClick="@{user.click}"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@{user.password}"/>

    </LinearLayout>

    </layout>
public class MainActivity extends AppCompatActivity {

    ListView list;
    List<User> data=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list=(ListView)findViewById(R.id.listView);
        data.add(new User("http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg","1","1"));
        data.add(new User("http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg","2","2"));
        data.add(new User("http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg","3","3"));
        data.add(new User("http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg","4","4"));
        list.setAdapter(new CommAdapter<User>(this,getLayoutInflater(),R.layout.item,BR.user,data));
    }
}
我們到這里主Activity就寫好了,主要看適配器,而且是可以復(fù)用的。因此適配器用泛型代替

這里new CommAdapter里面參數(shù)前兩個(gè)好理解,第三個(gè)R.layout.item是條目的布局,理解為item就上我們上面寫的,BR.user理解為那個(gè)User對(duì)象生成的viewmodel。

public class CommAdapter<T> extends BaseAdapter {

    private Context context;
    private LayoutInflater inflater;
    private int layoutId;
    private int variableId;//會(huì)自動(dòng)生成

    private List<T> list;

    public CommAdapter(Context context, LayoutInflater inflater, int layoutId, int variableId, List<T> list) {
        this.context = context;
        this.inflater = inflater;
        this.layoutId = layoutId;
        this.variableId = variableId;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewDataBinding dataBinding;
        if(convertView==null){
            dataBinding= DataBindingUtil.inflate(inflater,layoutId,parent,false);
        }else{
            //就重就之前的
            dataBinding=DataBindingUtil.getBinding(convertView);
        }
        dataBinding.setVariable(variableId,list.get(position));
        return dataBinding.getRoot().getRootView();
    }
}

這樣就可以直接運(yùn)行了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容