17

後,我的gradle AS版本升級到2.3.0, 數據綁定遭遇警告:數據綁定 - safeUnbox警告

警告:SelectMAP編程[指數]是一個盒裝的領域,但需要取消裝箱爲執行selectMap [index]? @android:顏色/白色:@android:顏色/透明。這可能會導致NPE,因此數據綁定將安全地解除它。你可以改變的表達,並明確包裹SelectMAP編程[指數]與safeUnbox(),以防止警告

SelectMAP編程是一個ObservableMap,然後我搜索這個警告,但僅獲得少量的討論,並沒有解決它

Android Studio 2.3.0-alpha1: Databinding + int unboxing causes compile errors

Databinding - data object is null on API 15-18

我遵循的聯繫方式,修改selectMap[index]safeUnbox(selectMap[index])但有語法錯誤。

那麼有誰知道如何解決這個警告?


編輯: 下面是XML文件中的代碼

<?xml version="1.0" encoding="utf-8"?> 

<data class="SupportCountryViewHolderBinding"> 

    <variable 
     name="viewModel" 
     type="com.goodarc.care_about.activity.account.support_country.SupportCountryHolderViewModel" /> 

    <variable 
     name="dataSource" 
     type="com.goodarc.care_about.module.assets_file.SupportCountry" /> 

    <variable 
     name="selectMap" 
     type="android.databinding.ObservableMap&lt;Integer, Boolean&gt;" /> 

    <variable 
     name="index" 
     type="int" /> 
</data> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@{selectMap[index] ? @android:color/white : @android:color/transparent}" 
    android:onClick="@{(v) -> viewModel.onItemSelectListener(selectMap, index)}" 
    android:orientation="vertical" 
    android:padding="20dp"> 

    <TextView 
     style="@style/TitleLabel2" 
     android:layout_gravity="center_vertical|start" 
     android:text="@{dataSource.display}" 
     android:textColor="@{selectMap[index] ? @android:color/black : @android:color/white}" 
     tools:text="Taiwan (+886)" /> 
</LinearLayout> 

構建是成功的,但警告出來(我過去的上方)。

+1

哪裏是你的問題的代碼? – pskink

回答

15

我有同樣的警告,在我的情況下改變從布爾類型布爾類型變量的聲明解決的問題:

來源:

<variable 
     name="readOnly" 
     type="Boolean" /> 

要:

<variable 
     name="readOnly" 
     type="boolean" /> 

所以,也許你可以嘗試:

<variable 
    name="selectMap" 
    type="android.databinding.ObservableMap&lt;Integer, boolean&gt;" /> 
+0

你有沒有與字符串相同的問題?在我的情況只是與布爾 –

+0

對不起,沒有問題,字符串它是別的東西AFAIR – Killer

4

您可以添加safeUnbox這樣的:

android:text="@{Double.toString(safeUnbox(product.listPrice))}" 
+0

我認爲safeUnbox是簡單的解決方案。 '''public static boolean safeUnbox(java.lang.Boolean boxed){return boxed == null?假:(布爾)盒裝; } android.databinding.DynamicUtil中的'''' – illusionJJ

0

BaseObservable這可能也發生。我需要將布爾類型更新爲布爾值。

@Bindable 
public boolean getAvoidXpressway() { 
    return commute.getAvoidXpressway(); 
} 

public void setAvoidXpressway(Boolean avoidXpressway) { 
    commute.setAvoidXpressway(avoidXpressway); 
    notifyPropertyChanged(BR.avoidXpressway); 
} 

如果你是綁定使用外部對象就像在我的情況下,確保類型返回也是布爾值;否則,警告將持續爆發。

0

添加safeUnbox()的警告變量將使這個警告過去了,它仍然運行良好

android:alpha="@{alpha != null ? safeUnbox(alpha) : 0.5f}"