Skip to content

Instantly share code, notes, and snippets.

@AdamSHurwitz

AdamSHurwitz/someLayout.md

Last active Dec 18, 2020
Embed
What would you like to do?
ODG - Android Data Binding Samples

Strings

  • Static: android:text="@string/sell_recommend_views_label"

  • Concat resources: android:text="@{'Hello ' + user.firstName}"

  • Concat resource and var (Include %1s formatting in String resource): android:text='@{String.format(@string/string_name, uxContent.reduceByPrice)}'

  • Formatted: android:text='@{@string/some_string(uxContent.someVal, uxContent.someVal)}'

  • Int resource ID: See Custom Attributes with BindingAdapters section.

  • Plurals

    • XML: android:text="@{uxContent.getCountLabel(context, uxContent.viewCount, @plurals/srp_miles)}"

    • Helper function:

      public String getCountLabel(Context context, String count, int label) {
          return context.getResources().getQuantityString(label, Integer.valueOf(count), Integer.valueOf(count));
       } 

Methods

  • Setting on view's method: android:onClick="@{() -> viewmodel.doSomething()}"

  • Pass context into method: android:text="@{uxContent.getDuration(context)}"

  • Pass view into method: android:onClick="@{(v) -> viewmodel.methodName(v)}"

  • Alternate syntax

    • XML:

      <layout xmlns:android="http://schemas.android.com/apk/res/android">
      
      <data>
          <variable name="handlers" type="com.example.MyHandlers"/>
      </data>
      
          <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@{user.firstName}"
              android:onClick="@{handlers::onClickFriend}"/>
      
       </layout>
    • Helper function:

      Public class MyHandlers {
          Public void onClickFriend(View view){...}
      }

Other

  • Two-way: android:text='@={viewmodel.someMutableLiveData}'

    • Nested LiveData: android:text='@={viewmodel.someMutableLiveData.anotherLiveData}'
  • Design value: android:text='@{var.value, tools="defaultValue"}'

  • Default value: android:text='@{var.value, default="defaultValue"}'

  • Nulls

    android:text="@{user.displayName ?? user.lastName}"
    android:text="@{user.displayName != null ? user.displayName : user.lastName}"
  • Reference other views in layout: android:onClick="@{(v) -> viewmodel.methodName(otherView.text)}"

  • Objects and safe unboxing: android:visibility="@{safeUnbox(Integer.valueOf(uxContent.bidCount)) > 0 ? View.VISIBLE : View.INVISIBLE}"

  • Casts: android:visibility="@{((String)(data.someValue)).length != 0 ? ... : ... }"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment