Android Data Binder 的一個bug,androidbinder

來源:互聯網
上載者:User

Android Data Binder 的一個bug,androidbinder

跟著官方教程學習資料繫結的用法,功能確實非常強大,這是 Android 向 MVVM 邁出的一大步,也是 Native 的開發方式逐漸向 Web 靠攏的一小步。

其中一個綁定方式是直接使用資源資料,例如:

android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"

官方教程:

完整版的布局檔案如下:

<layout xmlns:android="http://schemas.android.com/apk/res/android">    <data class="ResourceBinding">        <variable name="large" type="boolean" />    </data>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"            android:background="@android:color/black"            android:textColor="@android:color/white"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/hello_world" />    </LinearLayout></layout>

largePaddingsmallPadding 都是定義在 dimens.xml 檔案中的資源資料。

<dimen name="largePadding">20dp</dimen><dimen name="smallPadding">5dp</dimen>

在 Java 代碼中與綁定 large 變數,並賦值為 ture

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);   ResourceBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_resource);    binding.setLarge(true);} 

理論上,這樣做應該沒什麼問題,但是 Run 工程的時候,出現錯誤,報錯資訊如下:

cannot find the setter for attribute 'android:padding' on android.widget.TextView with parameter type float.

看來像是 DataBinder 把 @dimen/largePadding 解析成了 float 類型,可以試一下類型轉換:

android:padding="@{large? (int)@dimen/largePadding : (int)@dimen/smallPadding}"

編譯通過,運行結果也正確,應該是 DataBinder 出 bug 了,原來資源綁定還有這麼進階的用法,可以直接進行類型轉換 - (int)@dimen/largePadding

感覺好神奇,必須讀讀源碼,瞭解一下 DataBinder 的實現原理。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.