简书链接:databinding显示为null的特殊情况以及多种姿势的处理办法
文章字数:274,阅读全文大约需要1分钟

1
2
  app:text="@{model.nickname??@string/nologin}"
@{@string/young_zhiye(model.occupation)??@string/young_zhiye(``)```

上面的代码如果进入app能马上执行setModel()那么会完全正常的显示为未登录,

但是有一种情况是模型可能要过一段时间才调用setModel,会导致 app:text="@{@string/young_zhiye(model.occupation)??@string/young_zhiye(``)显示为职业显示为:null
那么需要改成这样,先判断model是否等于空!

第一次修改
1
app:text="@{model!=null?@string/young_zhiye(model.occupation):``}"

xml代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26



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

<TextView
android:layout_width="wrap_content"
app:text="@{model!=null&amp;&amp;model.title!=null?model.title:@string/young_tiele_empty}"
android:layout_height="wrap_content"
android:text=""
android:textColor="#999999"
android:textSize="13sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="职业:"
app:text="@{model!=null?(@string/young_zhiye(model.occupation)??@string/young_zhiye_empty):@string/young_zhiye_empty}"
android:textColor="#999999"
android:textSize="13sp"
/>

</LinearLayout>
第二次修改

经过第二次修改,变成了下面的这个样子才能解决为null又要使用个性化占位符的情况

1
app:text="@{model!=null?(@string/young_zhiye(model.occupation??@string/zanweitianxie)):@string/young_zhiye(@string/zanweitianxie)}"

表示如果model为空或者model.occupation为空就显示职业:暂未填写

第三次修改

第三次修改,如果服务器返回的是空字符串””那么这个写法也没法显示这种个性化为空 于是乎又改成了这样才能将才能解决问题。。。

1
2
app:text="@{model!=null?(TextUtils.isEmpty(model.occupation)?@string/young_zhiye(@string/zanweitianxie):@string/young_zhiye(model.occupation)):@string/young_zhiye(@string/zanweitianxie)}"