/var/log/messages

Jul 5, 2015 - 1 minute read - Comments - android

RecyclerView で onItemClick

ViewHolder で云々しろ、が定説らしい。とりあえず branch 作って作業開始。

$ git checkout -b onClick

基本的に

  • ViewHolder の属性で行なオブジェクト保持
  • ViewHolder のコンストラクタで setOnClickListener する
  • RecyclerView.Adapter#onBindViewHolder で行なオブジェクトの属性に取得した item を格納

というカンジにしといて onClick の中で行なオブジェクトを云々する方向なのか。

試行錯誤

とりあえず以下なカンジにしてたのですが

    public ViewHolder(View v) {
        super(v);
        view = v;
        view.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                //...
            }
        });
    }

駄目でした。レイアウトを見てみるに以下なカンジになっていたので

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="78dp"
        card_view:cardCornerRadius="4dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:id="@+id/cardView"
        android:clickable="true"
        android:focusable="True"
        android:foreground="?android:attr/selectableItemBackground"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/bg_main"
            android:padding="8dp">

            <TextView
                android:id="@+id/text1"
                android:textColor="@color/txt_main"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </RelativeLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

試しに clickable になってる CardView に OnClickListener 付けてみたら反応しました。てことは LinearLayout を clickable にして OnClickListener 付けたらどうなるのかな。

ヤッてみた

駄目でした。とりあえず CardView が拾えることは分かったのでヨシってことにします。インデクスが云々、ってのはその行のオブジェクトが取得できてるのでこれもヨシってことで良いのかどうか。

リポジトリは以下。

参考ドキュメント

以下です。

会議 週末メシ控え

comments powered by Disqus