Android 控件之 RecyclerView(一)—— 加载视图和布局选择

一、概述

RecyclerView 是在 Android5.0 之后,Google 推出的一个新控件,是作为 ListView、GridView 的替代者出现的。它具有比上述两者更高的灵活性,在功能上也更加强大。Google 官方对它的定义是:

A flexible view for providing a limited window into a large data set.
向一个有限的窗口(window)提供大量数据集的灵活视图(view)。

先来看看 RecyclerView 能实现哪些效果:
图1 图2
图3 图4
由于 RecylerView 定义在了 support 库中,如果我们想要使用 RecyclerView 控件,需要向项目中的 build.gradle添加代码 implementation ‘com.android.support:recyclerview-v7:27.1.1’ ,如下所示:

dependencies {
   
	implementation fileTree(include: ['*.jar'], dir: 'libs')
	implementation 'com.android.support:appcompat-v7:27.1.1'
	implementation 'com.android.support.constraint:constraint-layout:1.1.3'
	testImplementation 'junit:junit:4.12'
	androidTestImplementation 'com.android.support.test:runner:1.0.2'
	androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
	implementation 'com.android.support:recyclerview-v7:27.1.1'
}

添加完之后一定要记得点一下右上角的 Sync Now 进行同步,否则可能会出现错误。

二、列表视图的处理

1. item 的布局文件

首先,在 activity_main 中添加 RecyclerView 控件,代码如下:

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

其次,在 layout 文件夹下新建一个 Layout Resource file,命名为 item_recycler_view,它是 RecyclerView 中 item(即子项)的布局文件,我们需要的 item 布局为图片(ImageView)和文字(TextView)的组合,所以代码如下所示:

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

    <ImageView
        android:id="@+id/iv_item"
        android:layout_width="80dp"
        android:layout_height="80dp" />

    <TextView
        android:id="@+id/tv_item"
        
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值