Skip to content

Instantly share code, notes, and snippets.

@sahara-ooga
Last active January 1, 2020 03:33
Show Gist options
  • Save sahara-ooga/a33a326a9e421336177ff7718845eb0f to your computer and use it in GitHub Desktop.
Save sahara-ooga/a33a326a9e421336177ff7718845eb0f to your computer and use it in GitHub Desktop.
Data binding in Android

Activity

XMLファイルの設定

<layout> タグで囲む

activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android">

  <!--既存の実装-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
      ....
    </LinearLayout>
  <!--既存の実装ここまで-->
  
</layout>

onCreateでの設定

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        @Suppress("UNUSED_VARIABLE")
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
    }
}

Fragment

onCreateViewでの設定

例として、TitleFragment, fragment_title.xmlを用意した。

    /**Inflating and Returning the View with DataBindingUtil*/
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val binding = DataBindingUtil.inflate<FragmentTitleBinding>(
                inflater, R.layout.fragment_title, container, false
        )
        return binding.root
    }

activity_main.xmlでの設定

<layout xmlns:android="http://schemas.android.com/apk/res/android">

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

        <!-- Add a fragment tag for the titleFragment in the LinearLayout
             Use @+id/titleFragment for the android:id
             Use com.example.android.navigation.TitleFragment for the android:name
             Use match_parent for the layout_height and layout_width -->

        <fragment
            android:id="@+id/titleFragment"
            android:name="com.example.android.navigation.TitleFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></fragment>
    </LinearLayout>

</layout>

Reference

https://classroom.udacity.com/courses/ud9012/lessons/7466f670-3d47-4b60-8f6a-0914ce58f9ad/concepts/cda040dc-4139-4027-b8ee-d8119d451291

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