くま's Tech系Blog

基本的には技術で学んだことを書き留めようと思います。雑談もやるかもね!

RecyclerViewを使ってみた

ListViewに比べてRecyclerViewの方が使い勝手がいいので、試しに使ってみました。 カスタマイズできるのがいいですね!

①レイアウトの作成

まずは表示する1列分のレイアウトを作成します。

article_content.xml

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

        <TextView
            android:id="@+id/titleView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"/>

        <TextView
            android:id="@+id/dateView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"/>
</LinearLayout>

そして、RecyclerViewのレイアウトを作成します。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="?android:attr/selectableItemBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/articlRecyclerView"
        android:layout_width="390dp"
        android:layout_height="583dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

②Adapterの作成

class ArticlesAdapter(private val context: Context,
                      private val articles: List<Article>,
                      private val articleClicked: (Article) -> Unit) : RecyclerView.Adapter<ArticlesAdapter.ArticleViewHolder>() {

    class ArticleViewHolder(view: View, val articleClicked: (Article) -> Unit): RecyclerView.ViewHolder(view) {
        val title = view.findViewById<TextView>(R.id.titleView)
        val date = view.findViewById<TextView>(R.id.dateView)

        fun setUp(article: Article) {
            this.itemView.setOnClickListener { articleClicked(article) }
        }
    }

    override fun getItemCount(): Int = articles.size

    //1行表示するたびに呼ばれレイアウトを生成してViewHolderを生成して返す
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
        val rowView = LayoutInflater.from(context).inflate(R.layout.article_content, parent, false)

        return ArticleViewHolder(rowView, articleClicked)
    }

    override fun onBindViewHolder(holder: ArticleViewHolder?, position: Int) {
        holder!!.let {
            it.title.text = articles[position].title
            it.date.text = DateFormat.format("yyyy/MM/dd HH:mm",articles[position].date).toString()
            it.url.text = articles[position].link
        }

        holder.setUp(articles[position])
    }
}

コンストラクタでcontextと一覧のデータ、タップ時のコールバックを受け取るようにしています。 getItemCount()メソッドで表示件数を取得しています。 onCreateViewHolder()メソッドでviewを生成しています。①で作成した1列分のレイアウトと紐づけを行い、ViewHolderを返しています。 onBindViewHolder()メソッドではデータをタップしたときの処理を記載しています。

③Activityの作成

最後に一覧として表示されるようにActivityを作成します。

class ListArticlesActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_article_list)
        articlRecyclerView.layoutManager = LinearLayoutManager(this)
        articlRecyclerView.adapter = ArticlesAdapter(this, data.articles) {
            // タップしたときの処理を記載
        }   
    }
}

LinearLayoutManagerのインスタンスを生成し、自作したArticlesAdapterを適用させています。 GridLayoutManagerなどの種類があるので、使いたいものをでインスタンス化します。 ②のコンストラクタにタップしたときの処理を入れているので、この画面でタップしたときの処理を書きます。

これで最低限の表示はできると思います。 画像を表示させるとか使ってみたいですね。 あとはDataBindingとかも 実際使ってみて、ListViewよりは制約がなく、幅広いレイアウトが作れそうな印象です。

参照

【kotlin】RecyclerViewの簡単な使い方【初心者向け】 LinearLayoutManager