2016-03-25 9 views
5

理解できません...変数フィールドがnullでない場合にのみビューのプロパティを設定する方法はありますか?
データバインディング:NULLでない場合はプロパティを設定

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

    <data> 
     <variable 
      name="item" 
      type="com.test.app.Item" /> 
    </data> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="60dp" 
     android:orientation="horizontal"> 

     <ImageView 
      android:id="@+id/icon" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:layout_centerVertical="true" 
      android:layout_margin="16dp" 
      android:src="@{item.getDrawable()}"/> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:layout_marginEnd="16dp" 
      android:layout_marginLeft="72dp" 
      android:layout_marginRight="16dp" 
      android:layout_marginStart="72dp" 
      android:layout_toLeftOf="@id/action" 
      android:layout_toStartOf="@id/action" 
      android:orientation="vertical"> 

      <TextView 
       android:id="@+id/text1" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:singleLine="true" 
       android:textColor="@color/black_87" 
       android:textSize="16sp" 
       android:text="@{item.getTitle()}"/> 

      <TextView 
       android:id="@+id/text2" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:autoLink="web|email" 
       android:linksClickable="false" 
       android:singleLine="true" 
       android:textColor="@color/black_54" 
       android:textSize="14sp" 
       android:text="@{item.getSubtitle()}"/> 


     </LinearLayout> 

    </RelativeLayout> 
</layout> 

ための項目のいくつかのフィールドはnullにすることができ、私は不必要にレイアウトビューのメソッドを呼び出すことはありません。そして私はNullPointerExceptionを手に入れません。ヌルでない場合にのみ、どのようにプロパティを設定できますか? S.英語のために申し訳ありません。

答えて

24

Wellデータバインディングは、一般的にNullPointerExceptionをチェックし、itemがnullの場合でもデフォルト値(nullなど)を割り当てます。

しかし、アイテムのプロパティにnullチェックのための基本的な例:

android:text='@{item.title != null ? user.title : ""}' 

または「ヌル合体演算子」を使用します。ヌル集合演算子(??)は、左オペランドがヌルでない場合はそれを選択し、ヌルの場合は右を選択します。

android:text='@{item.title ?? ""}' 

titleまたはgetTitleは関係ないことに注意してください。

+0

私はそれを知っています。値がnullの場合、Viewでメソッドを呼び出さないことは不可能です。 –

+1

すみません、あなたがここで何を求めているのか分かりません。新しい値がnullの場合、以前の値を保持しようとしていますか?これがデータバインディングを介して達成するための良い方法であるとは確信していません。新しい双方向データ・バインディングは、nullでないときはいつでも、(おそらく他の)オブジェクトの値を設定することによって推測できます。しかし、私はこれが良い方法だとは思わない。 –

+1

代わりに代わりに使用される変数を分割し、代わりに各プロパティに1つずつ設定する方法があります。 Itemの代わりにStringを入力します。 –

関連する問題