3
1

More than 3 years have passed since last update.

【翻訳】RecyclerView の高度なカスタマイズ

Posted at

ReciclerViewをカスタマイズする必要があり、公式を調べていたら英語ページに当たったので翻訳しました。

[Android Developers > ドキュメント > ガイド > 主要トピック > ユーザーインターフェース > レイアウト > RecyclerView の高度なカスタマイズ] Advanced RecyclerView customization

RecyclerView の高度なカスタマイズ

You can customize the RecyclerView objects to meet your specific needs. The standard classes described in Create dynamic lists with RecyclerView provide all the functionality that most developers will need; in many cases, the only customization you need to do is design the view for each view holder and write the code to update those views with the appropriate data. However, if your app has specific requirements, you can modify the standard behavior in a number of ways. This page describes some of the other possible customizations.

RecyclerView オブジェクトは必要に応じカスタマイズすることができます。RecyclerView でリストを作成する で説明された基本的なクラスで、ほとんどの開発者が必要とするすべての機能を網羅します。たいていの場合、あなたがしなければならないカスタマイズは、それぞれのビューホルダーのためのビューをデザインし、これらのビューを適当なデータで更新するコードを書くことだけです。しかしながら、アプリが特定の要求を持つ場合、いくつかの方法で基本的な動作を変更することができます。このページでは他にできるいくつかのカスタマイズについて説明します。

レイアウトを変更する

Modifying the layout

The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups. The Android Support Library includes three standard layout managers, each of which offers many customization options:

RecyclerView はレイアウトマネージャーを使用して個々のアイテムを画面に配置し、アイテムがユーザーから見えなくなった場合にビューを再利用するタイミングを定義します。ビューを再利用(または再資源化)するために、レイアウトマネージャーはアダプターにビューのコンテンツをデータセットの異なる要素で置換するかを確認します。この挙動でビューをリサイクルすることで、不要なビューを生成したり、高コストな findViewById() 検索の実行を避け、パフォーマンスを改善します。Android サポートライブラリは3つの標準的なレイアウトマネージャーを持ち、そのどれもが様々なカスタマイズ用オプションを提供します。

  • LinearLayoutManager arranges the items in a one-dimensional list. Using a RecyclerView with LinearLayoutManager provides functionality like the older ListView layout.
  • GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.
  • StaggeredGridLayoutManager arranges the items in a two-dimensional grid, with each column slightly offset from the one before, like the stars in an American flag.
  • LinearLayoutManager はアイテムを一次元のリストとして並べます。RecyclerViewLinearLayoutManager と組み合わせることで、以前の ListView レイアウトのような機能を使用できます。
  • GridLayoutManager はアイテムをチェッカー盤のマスのように、二次元のグリッドとして並べます。RecyclerViewGridLayoutManager と組み合わせることで、以前の GridView レイアウトのような機能を使用できます。
  • StaggeredGridLayoutManager はアイテムを二次元のグリッドとして、各列が前の列と少しずつずれてちょうどアメリカ国旗の星のように並べます。

If none of these layout managers suits your needs, you can create your own by extending the RecyclerView.LayoutManager abstract class.

これらのレイアウトマネージャーでは要件を満たさないのであれば、抽象クラスであるRecyclerView.LayoutManager を継承して独自のものを作成できます。

アニメーションを追加する

Add item animations

Whenever an item changes, the RecyclerView uses an animator to change its appearance. This animator is an object that extends the abstract RecyclerView.ItemAnimator class. By default, the RecyclerView uses DefaultItemAnimator to provide the animation. If you want to provide custom animations, you can define your own animator object by extending RecyclerView.ItemAnimator.

アイテムが変化する際は必ず、 RecyclerView は見た目を変化させるための アニメーター を使用します。このアニメーターは抽象クラスである RecyclerView.ItemAnimator を継承したオブジェクトです。デフォルトでは RecyclerViewDefaultItemAnimator を使用してアニメーションを提供します。もしカスタムアニメーションを利用したい場合は、RecyclerView.ItemAnimator を継承して独自のアニメーターオブジェクトを定義できます。

リスト要素の選択を可能にする

Enable list-item selection

The recyclerview-selection library enables users to select items in RecyclerView list using touch or mouse input. You retain control over the visual presentation of a selected item. You can also retain control over policies controlling selection behavior, such as items that can be eligible for selection, and how many items can be selected.

To add selection support to a RecyclerView instance, follow these steps:

recyclerview-selection ライブラリにより、ユーザーはタッチまたはマウスを使用して RecyclerView リストのアイテムを選択することができます。選択されたアイテムの表示は引き続き制御できます。また、選択可能なアイテムや選択できる数といった動作を制御するポリシーも引き続きコントロール可能です。

RecyclerView インスタンスに selection support を追加するには、次のステップに従います:

  1. Determine which selection key type to use, then build a ItemKeyProvider.

There are three key types that you can use to identify selected items: Parcelable (and all subclasses like Uri), String, and Long. For detailed information about selection-key types, see SelectionTracker.Builder.

  1. Implement ItemDetailsLookup.

  2. ItemDetailsLookup enables the selection library to access information about RecyclerView items given a MotionEvent. It is effectively a factory for ItemDetails instances that are backed up by (or extracted from) a RecyclerView.ViewHolder instance.

  3. Update item Views in RecyclerView to reflect that the user has selected or unselected it.

The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder(). The recommended approach is as follows:

  • In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
  • Update the styling of the view to represent the activated status. We recommend you use a color state list resource to configure the styling.
  1. Use ActionMode to provide the user with tools to perform an action on the selection.

  2. Register a SelectionTracker.SelectionObserver to be notified when selection changes. When a selection is first created, start ActionMode to represent this to the user, and provide selection-specific actions. For example, you may add a delete button to the ActionMode bar, and connect the back arrow on the bar to clear the selection. When the selection becomes empty (if the user cleared the selection the last time), don't forget to terminate action mode.

  3. Perform any interpreted secondary actions

  4. At the end of the event processing pipeline, the library may determine that the user is attempting to activate an item by tapping it, or is attempting to drag and drop an item or set of selected items. React to these interpretations by registering the appropriate listener. For more information, see SelectionTracker.Builder.

  5. Assemble everything with SelectionTracker.Builder

  6. The following example shows how to put these pieces together by using the Long selection key:

  7. KOTLINJAVA

  8. In order to build a SelectionTracker instance, your app must supply the same RecyclerView.Adapter that you used to initialize RecyclerView to SelectionTracker.Builder. For this reason, you will most likely need to inject the SelectionTracker instance, once created, into your RecyclerView.Adapter after the RecyclerView.Adapter is created. Otherwise, you won't be able to check an item's selected status from the onBindViewHolder() method.

  9. Include selection in the activity lifecycle events.

  10. In order to preserve selection state across the activity lifecycle events, your app must call the selection tracker's onSaveInstanceState() and onRestoreInstanceState() methods from the activity's onSaveInstanceState() and onRestoreInstanceState() methods respectively. Your app must also supply a unique selection ID to the SelectionTracker.Builder constructor. This ID is required because an activity or a fragment may have more than one distinct, selectable list, all of which need to be persisted in their saved state.

  1. 使用する選択キーを定義し、その上で ItemKeyProvider を構築する
    選択されたアイテムを識別するために使用できるキーは3種類あります。Parcelable(と Uri 等のすべてのサブクラス)、StringLong です。選択キータイプの詳細な情報は、selectionTracker.Builder を参照してください。

  2. ItemDetailsLookup を implement する
    ItemDetailsLookup により、selection ライブラリは MotionEvent から与えられる RecyclerView アイテムについての情報にアクセスできます。これは RecyclerView.ViewHolder インスタンスによりバックアップ(または抽出された) ItemDetails インスタンスを効果的に作成します。

  3. RecyclerView 内のアイテム Views を、ユーザーの選択または選択解除を反映するよう更新する
    selection ライブラリは選択されたアイテムのためのデフォルト表示を提供しませんが、onBindViewHolder() を implement する際はこれを提供しないとなりません。推奨される方法は次の通りです:

    • onBindViewHolder() 内で、View オブジェクトに対し setActivated()(※setSelected() ではない)を(アイテムが選択されているかどうかによって) truefalse と一緒に呼び出します。
    • アクティベート状態を表現するためのビューのスタイルを更新します。スタイル設定には カラー状態リストリソース を使用することを推奨します。
  4. ユーザーに選択時の動作を実行するツールを提供するために ActionMode を使用する
    selection が変化した際に通知する SelectionTracker.selectionObserver を登録します。最初に selection が生成されたときに、これをユーザーに明示する為に ActionMode を開始し、selection 特有の動作を提供します。例えば ActionMode バーに削除ボタンを追加し、バー上の戻る矢印記号を selection のクリアに紐づけることができます。selection が空になったとき(ユーザーが最後に selection をクリアした場合)は、 ActionMode を消去するのを忘れないようにしてください。

  5. インタープリタで二次的な動作を実行する
    一連のイベントプロセスの最後には、ライブラリはユーザーがアイテムをタップすることでアクティベートしようとしたのか、アイテムまたは選択されたアイテム群をドラッグ&ドロップしようとしたのかを判定します。これらの解釈に対し、適切なリスナーを登録して対応します。より詳しい情報は selectionTracker.Builder を参照してください。

  6. 全てをselectionTracker.Builder と一緒にアセンブルする
    下記の例は Long 型の selection キーを使用してこれらのパーツをまとめる方法を示しています:
    KOTLIN / JAVA
    SelectionTracker インスタンスを構築するために、アプリは RecyclerView を初期化するのに使用したのと同じ RecyclerView.AdapterSelectionTracker.Builder に渡さなければなりません。このため、おそらくSelectionTracker インスタンスを一旦生成し、RecyclerView.Adapterが生成された後で RecyclerView.Adapter に挿入する必要があります。一方で、 onBindViewHolder() メソッドからアイテムの選択状態を確認することはできません。

  7. アクティビティのライフサイクルイベントの中に selection を含める
    アクティビティのライフサイクル を通して選択状態を保存するため、アプリはアクティビティの onSaceInstanceState()onResotreInstanceState() のそれぞれから、 SelectionTracker の onSaveInstanceState()onRestoreInstanceState() メソッドを呼ぶ必要があります。また、SelectionTracker.Builder のコンストラクタに対し一意の selection ID を渡さなければなりません。この ID はアクティビティやフラグメントが、saved state に保持される必要のあるすべての、1つ以上の明確な、選択可能なリストを持つために必須となります。


RecyclerView のカスタマイズを色々と調べているのですが、なかなか難しいですね。(ちょっと特殊な要件があるのも一因ですが)

ドキュメントを読んでもわかったような、わからないような…
手を動かした内容もそのうちQiitaに書き残したいところです。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1