android黑科技——完美解決界面邏輯的數據框架DataBinding(最新)的使用(一)


dataBinding框架是在2015年谷歌I/O大會上被官方推出的非常厲害的新框架,這個框架給我們帶來了很多的方便,不僅簡化了頻繁地findViewById,還增加了代碼的耦合性。說到這里,其實網上也有很多快速的注解框架,還有一些第三方插件,之前我也有用過插件方法,但是比起dataBinding框架,還是不好用。而且官方文檔上明確標注,這個框架還可以加快xml的解析速度,如此神奇的框架,怎能不先體驗一番呢?

盡管如此好用,但是還沒有火到某種程度,的確在網上搜不出很多關於這個框架的使用例子,搜到的也大多是比較陳舊的。而且據我了解,大家普遍習慣了原有的findViewById的邏輯思維,只把dataBinding作為寫着玩玩,在實際項目中很少使用。即使如此,但是隨着時間的推移,我依然相信這個框架會達到android界家喻戶曉的地步。

好了,言歸正傳,下面來看看到底如何使用它。

首先你得把你的android studio升級到1.5以上,這個親兒子,就不多說了,目前官方已經更新到了2.n的版本,還在使用eclipse的,趕緊飛過來吧。

現在的studio版本已經加入了dataBinding框架的自動提示,肯定在推薦大家使用啦。

具體使用:

1)首先在app的Module.gradle文件中的android標簽下添加

dataBinding{
enabled = true
}

具體如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"


    defaultConfig {
        applicationId "com.example.nanchen.databindingdemo"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    dataBinding{
        enabled = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
}

 

 

再同步編譯,第一次可能比較慢,因為dataBinding放在網絡上,同步好后就可以在整個工程中使用了。

 

2)然后建立一個java bean,這里就用一個簡單的用戶類,其中加了兩個方法用於事件綁定,具體看后面基本解釋。

 1 package com.example.nanchen.databindingdemo;
 2 
 3 import android.view.View;
 4 import android.widget.Toast;
 5 
 6 /**
 7  *
 8  * Created by 南塵 on 16-7-18.
 9  */
10 public class User {
11     private String name;//用戶名
12     private String nickName;//昵稱
13     private String email;//郵箱
14 
15     private boolean vip;//是否是會員
16     private int level;//級別
17 
18     public int getLevel() {
19         return level;
20     }
21 
22     public void setLevel(int level) {
23         this.level = level;
24     }
25 
26     public boolean isVip() {
27         return vip;
28     }
29 
30     public void setVip(boolean vip) {
31         this.vip = vip;
32     }
33 
34     public User() {
35     }
36 
37     public User(String name, String nickName, String email) {
38         this.name = name;
39         this.nickName = nickName;
40         this.email = email;
41     }
42 
43     public String getEmail() {
44         return email;
45     }
46 
47     public void setEmail(String email) {
48         this.email = email;
49     }
50 
51     public String getName() {
52         return name;
53     }
54 
55     public void setName(String name) {
56         this.name = name;
57     }
58 
59     public String getNickName() {
60         return nickName;
61     }
62 
63     public void setNickName(String nickName) {
64         this.nickName = nickName;
65     }
66 
67     public void clickName(View view){
68         Toast.makeText(view.getContext(),"點擊了用戶名",Toast.LENGTH_SHORT).show();
69     }
70 
71     public boolean longClickNickName(View view){
72         Toast.makeText(view.getContext(),"長按了昵稱!",Toast.LENGTH_SHORT).show();
73         return true;
74     }
75 }

 

3)下面看看xml布局是如何布局的

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="user"
            type="com.example.nanchen.databindingdemo.User">
        </variable>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        tools:context="com.example.nanchen.databindingdemo.MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:onClick="@{user.clickName}"
            android:textColor="@{user.vip? 0xffff0000:0xff000000}"
            android:text="@{user.nickName + `(` + user.name +`)`}"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:onLongClick="@{user.longClickNickName}"
            android:text="@{user.nickName ?? user.name}"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:textColor="@{user.level &lt; 3 ? 0xff03bbf9 : 0xfff60bdb }"
            android:text="@{user.email}"/>
    </LinearLayout>
</layout>

大家仔細一看會發現沒有Id,而且文本是通過@{}這樣的方式指定的,並且原來的LineaLayout並沒作為根節點,而換成了layout,並且加入了data標簽,data標簽用於綁定dataBean,並且是支持<import>標簽的,具體有部分不理解請看下面的基本解釋

4)再來看看怎么把值傳進去的,在Activity中

 

package com.example.nanchen.databindingdemo;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.example.nanchen.databindingdemo.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();
        user.setName("劉世麟");
        user.setNickName("南塵");
        user.setEmail("liushilin@qq.com");
        user.setVip(true);
        user.setLevel(5);
        binding.setUser(user);

//        binding.setUser(new User("劉世麟","南塵","liushilin@qq.com"));
    }
}

5)下面看看運行結果

可以看到其中的用戶名和郵箱版塊都變了顏色,這是在xml中有做設置的。具體繼續看下面的解釋。

 

6)簡單解釋

①dataBinding在xml文件是支持import,可以導入java支持的包,所以也就可以進行簡單的運算,比如上面的xml中就用了三元運算符

android:textColor="@{user.vip? 0xffff0000:0xff000000}"

當導入的用戶是vip的時候,文本顏色會設置為紅色,當不是vip的時候會顯示黑色

②而且支持java的字符串拼接

android:text="@{user.nickName + `(` + user.name +`)`}"

細心的網友肯定會發現,這個字符串拼接的時候用到的里面不是單引號‘,而是一個數字鍵1左邊那個鍵`。

其中在dataBinding的xml文件中,是不支持雙引號中加單引號的,但是支持單引號中加雙引號,在雙引號中可以加`;

③細心的網友還會發現xml中有這樣一句話

android:text="@{user.nickName ?? user.name}"

這里用了雙冒號??代表的意思是,如果user.nickName為空,則顯示user.name,如果不為空,則顯示nickName;

其中這句話等於  user.nickName == null ? user.name : user.nickName;

④既然這是xml布局,大家肯定知道在xml中是不允許用<>的,用的話會被默認是標簽,那么如果一定要用<>做比較表達式呢,這里可以使用轉義來解決。

代碼中有這樣一句話:

android:textColor="@{user.level &lt; 3 ? 0xff03bbf9 : 0xfff60bdb }

其中的&lt; 代表的就是小於符號<,意思是如果用於等級小於3,則郵箱文本為藍色,否則文本為紫色。

⑤而我們實際運用中肯定也會有很多的點擊事件,那么如何實現點擊事件的呢?

這就是我們為什么在dataBean實體類User中添加了兩個方法的原因

public void clickName(View view){
        Toast.makeText(view.getContext(),"點擊了用戶名",Toast.LENGTH_SHORT).show();
    }

    public boolean longClickNickName(View view){
        Toast.makeText(view.getContext(),"長按了昵稱!",Toast.LENGTH_SHORT).show();
        return true;
    }

這兩個方法其實不一定寫在實體類中,其實寫在其他類中也是可以的,不過我更推薦寫在實體類中,因為觸發事件的時候,很有可能會用到實體類的其他屬性,寫在這里面調用起來就變得比較輕松了。

然后再把事件和xml中綁定在一起

     <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:onClick="@{user.clickName}"
            android:textColor="@{user.vip? 0xffff0000:0xff000000}"
            android:text="@{user.nickName + `(` + user.name +`)`}"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:onLongClick="@{user.longClickNickName}"
            android:text="@{user.nickName ?? user.name}"/>

 

這個中間有onClick和onLongClick用於綁定。

值得注意的是!!!!!

這里的onclick方法或者是其他的觸發事件的方法的返回值類型和參數類型和個數必須一致,否則一定會報錯

 

上面就是dataBinding的一些簡單使用

 

項目已同步至github官網,下載地址和具體詳情擴展還請看使用二:http://www.cnblogs.com/liushilin/p/5683721.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM