美文网首页
Android控件RecyclerView实践 2019-12-

Android控件RecyclerView实践 2019-12-

作者: 勇往直前888 | 来源:发表于2019-12-06 18:37 被阅读0次

依赖库

app/build.gradle中的dependencies闭包添加以下内容:

    // 瀑布流控件
    implementation 'com.android.support:recyclerview-v7:28.0.0'

然后点击顶部的Sync Now进行同步

添加页面

新建一个页面,比如就叫PhotoActivity,创建相应的java, xml文件。在首页中加一个按钮,点一下,就跳转过去。在AndroidManifest.xml中声明

        <!-- 照片墙,瀑布流 -->
        <activity android:name=".PhotoActivity">
        </activity>
  • xml中将RecyclerView添加进去
<?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">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

单元格

每一张照片是什么样子的,这也需要对应的java,xml文件

  • java文件名字就叫PhotoItem,只有图片名字和图片url两个成员
public final class PhotoItem {
    private String name;
    private String imageUrl;

    public PhotoItem(String name, String imageUrl){
        this.name = name;
        this.imageUrl = imageUrl;
    }

    public String getName() {
        return name;
    }

    public String getImageUrl() {
        return imageUrl;
    }
}
  • xml文件就叫item_photo.xml,只有图片和文字两个组件
<?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">

    <ImageView
        android:id="@+id/image_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/text_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        />

</LinearLayout>

创建ViewHolder

  • RecyclerView.ViewHolder,其实就是从单元格(这里是item_photo.xml)资源文件读取各个资源。

  • 名字就叫PhotoViewHolder好了。

public final class PhotoViewHolder extends RecyclerView.ViewHolder {
    private ImageView photoImageView;
    private TextView nameTextView;

    public PhotoViewHolder(@NonNull View itemView) {
        super(itemView);

        photoImageView = (ImageView)itemView.findViewById(R.id.image_item);
        nameTextView = (TextView)itemView.findViewById(R.id.text_item);
    }
    
    public void setName(String name) {
        if (name != null) {
            nameTextView.setText(name);  
        }
    }
    
    public void setImage(Bitmap bitmap) {
        if (bitmap != null) {
            photoImageView.setImageBitmap(bitmap);
        }
    }
}

创建适配器

  • RecyclerView.Adapter为基类。

  • 数据源,一般是一个数组,作为Adapter的成员,由外部提供,用来展示数据。

  • 有三个方法需要重写,分别是单元的创建,绑定,个数。

  • 名字就叫PhotoAdapter

public final class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> {
    private List<PhotoItem> items;
    public PhotoAdapter(List<PhotoItem> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false);
        PhotoViewHolder holder = new PhotoViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final PhotoViewHolder holder, int position) {
        PhotoItem item = items.get(position);
        String url = item.getImageUrl();
        String name = item.getName();
        holder.setName(name);
        BitmapLoader loader = BitmapLoader.getInstance();
        loader.loadBitmap(url, new BitmapLoader.BitmapLoaderCallback() {
            @Override
            public void success(Bitmap bitmap) {
                holder.setImage(bitmap);
            }

            @Override
            public void failure(String message) {
                // 什么也不做
            }
        });
    }

    @Override
    public int getItemCount() {
        return items.size();
    }
}

这里的BitmapLoader是自己写的一个从网络加载图片的缓存工具。

列表形式展示

Activity中将RecyclerView,Adapter,List<Item>数据等整合起来,就能展示数据。数据展示方式由LayoutManager决定。如果是列表展示,用LinearLayoutManager就可以了。

public final class PhotoActivity extends Activity {
    private List<PhotoItem> items = new ArrayList<PhotoItem>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_photo);

        initItems();

        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        PhotoAdapter photoAdapter = new PhotoAdapter(items);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(photoAdapter);
    }

    private void initItems() {
        for (int i = 0; i < 10; i++) {
            String name = StrConstant.getStringByRandom();
            String url = UrlConstant.getUrl();
            PhotoItem item = new PhotoItem(name, url);
            items.add(item);
        }
    }
}

这里的StrConstant, UrlConstant是自定义的工具。

  • 列表显示和ListView的效果是一样的
企业微信截图_2e7d9fd6-cc76-4436-a894-f159e114dbc0.png

列表横向滑动

只要添加一句话linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);列表就变成横向滑动了。当然布局要稍微调整一下。

企业微信截图_556b177e-32b9-4a46-87af-87f9951d8d97.png

网格显示

只要换下LayoutManager就可以了。

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
image.png

由于照片大小不一样,有大量的空白。

瀑布流显示

只要换下LayoutManager就可以了。

        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);;
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
企业微信截图_99dc01ee-ff2f-4ae7-9598-1425ea3e9fd0.png

空白比网格布局相对来说要少一点。

如果图片差不多大,那么看上去感觉会好一点,这时和网格布局也差不多:

企业微信截图_54ec9b0a-a3be-4760-8369-59d64341e757.png

点击事件

在创建view holder的时候,用代码添加

    @NonNull
    @Override
    public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false);
        final PhotoViewHolder holder = new PhotoViewHolder(view);
        // 点击事件
        ImageView imageView = holder.getPhotoImageView();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                PhotoItem item = items.get(position);
                Toast.makeText(CacheDemoApplication.getContext(), "点击了图片:" + item.getName(), Toast.LENGTH_LONG).show();
            }
        });
        return holder;
    }

参考文章

RecyclerView
Activity 一 : 手动创建一个Activity

相关文章

网友评论

      本文标题:Android控件RecyclerView实践 2019-12-

      本文链接:https://www.haomeiwen.com/subject/mbzdgctx.html