いろいろ備忘録

雑記です。

データバインディングでOrmaとRecyclerView

Ormaの公式のexampleを再現する形でやっていきます。

Ormaは入っていて、モデルを作ってビルドした後という前提です。

exampleではTodoモデルなので、適宜使用するモデルに変更しましょう。 

 

1.build.gradleにバインディング設定を追記。CardViewとRecyclerViewも書いておく。

Android Databinding 〜超入門〜 - Qiita

implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'


2.フラグメントを作成し、xmlのルートをFrameLayoutからlayoutに変更し、ルートのwidthとheight属性、TextViewも消す。RecyclerViewを足す。

参考:

Android-Orma/fragment_recycler_view.xml at master · maskarade/Android-Orma · GitHub

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.android.プロジェクト名.なんたらFragment">

<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eee"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
/>

</layout>

 

3.公式を参考にFragmentのjavaの方の必要なさそうなソースを消しておく。

Android-Orma/RecyclerViewFragment.java at master · maskarade/Android-Orma · GitHub

 

4.CardViewのXMLをlayoutディレクトリに作成する。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
>
<data>
<variable name="user" type="com.example.android.パッケージ名.infra.entity.User" />
</data>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="2dp"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:text="@{user.name}"
/>
</android.support.v7.widget.CardView>
</layout>

 

5.VH、Adapterの順にコピペしてくる。

Android-Orma/RecyclerViewFragment.java at master · maskarade/Android-Orma · GitHub

6.onCreateViewをいい感じにする。

7.Activityに作ったフラグメントを紐付ける。

このとき、Fragment側で継承しているフラグメントがサポートライブラリならgetSupportFragmentManager()を使用しないとaddが解決出来ない。

 

以上です。

getItemCount()などでUIスレッドからOrmaを利用するため、OrmaDatabaseの生成時に実行スレッドの制約をしていると落ちるので気をつけてください。

 

制約を外すよりもっといいやり方があったら教えてくれると幸いです。