android v7兼容包RecyclerView的使用(一)
什么是RecyclerView?个人理解,它是一个在数据量大的时候,为了显示在界面上提供的灵活高效处理的控件。可以替代listview,gallery,gridview等控件。
如何使用?本篇文章只是热热身,不会过多介绍细节。
首先需要导入\sdk\extras\android\support\v7\recyclerview\libs\android-support-v7-recyclerview.jar包,如果sdk目录下没有该文件,则adt版本可能太低,建议升级或者从网上下载该库。
RecyclerView的使用准备多谢几篇,所以这篇只是入门。
国际惯例,先看效果图,此程序实现微信的会话记录界面。
分析一下,该界面的每一项都是由四个组件构成,即图标,标题,描述,时间。所以,开始编写实体类。
package cn.edu.zafu.recyclerviewdemo;
/**
* 实体类
* @author lizhangqu
*
* 2015-3-10
*/
public class Item {
//图标,简单起见存在本地drawable目录
private int img;
//标题
private String title;
//描述
private String description;
//时间
private String time;
//getter 和 setter
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public String toString() {
return "Item [img=" + img + ", title=" + title + ", description="
+ description + ", time=" + time + "]";
}
}
编写完实体类后,开始对每一项的布局进行编写,使用相对布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp" >
<ImageView
android:id="@+id/img"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="@drawable/icon" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@id/img"
android:text="微信支付"
android:textColor="#000"
android:textSize="16sp" />
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:text="晚上20:09"
android:textColor="#777"
android:textSize="12sp" />
<TextView
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/title"
android:layout_below="@id/title"
android:layout_marginTop="5dp"
android:text="微信支付:支付成功通知" />
</RelativeLayout>
编写适配器,并编写接口处理点击事件
package cn.edu.zafu.recyclerviewdemo;
import java.util.List;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import cn.edu.zafu.recyclerviewdemo.RecyclerAdapter.ItemViewHolder;
public class RecyclerAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<Item> items;
//点击监听事件
interface OnRecyclerViewItemClickListener{
void onClick(View view,int position);
};
private OnRecyclerViewItemClickListener listener;
//设置监听器
public void setListener(OnRecyclerViewItemClickListener listener) {
this.listener = listener;
}
//构造函数,将数据赋值给成员变量
public RecyclerAdapter(List<Item> items) {
this.items = items;
}
//获得数据大小
@Override
public int getItemCount() {
return items.size();
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//将布局进行绑定
View view = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.item, viewGroup, false);
return new ItemViewHolder(view);
}
//绑定数据
@Override
public void onBindViewHolder(final ItemViewHolder viewHolder,final int position) {
Item item = items.get(position);
viewHolder.img.setImageResource(item.getImg());
viewHolder.title.setText(item.getTitle());
viewHolder.description.setText(item.getDescription());
viewHolder.time.setText(item.getTime());
viewHolder.itemView.setOnClickListener(new OnClickListener() {
//如果监听器非空,则回调
@Override
public void onClick(View v) {
if (listener!=null) {
listener.onClick(viewHolder.itemView, position);
}
}
});
}
//ViewHolder,用于缓存,提高效率
public final static class ItemViewHolder extends RecyclerView.ViewHolder {
//每一项的四个控件
ImageView img;
TextView title;
TextView description;
TextView time;
public ItemViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img);
title = (TextView) itemView.findViewById(R.id.title);
description = (TextView) itemView.findViewById(R.id.description);
time = (TextView) itemView.findViewById(R.id.time);
}
}
}
在Activity中使用,为recyclerview设置适配器,数据改变时的动画,
package cn.edu.zafu.recyclerviewdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import cn.edu.zafu.recyclerviewdemo.RecyclerAdapter.OnRecyclerViewItemClickListener;
public class MainActivity extends Activity {
private RecyclerView recyclerView;
private ArrayList<Item> items = new ArrayList<Item>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);initDatas();
setContentView(R.layout.activity_main);
initDatas();//初始化数据
initViews();//初始化recyclerview
}
private void initViews() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//新建适配器
RecyclerAdapter adapter = new RecyclerAdapter(items);
//设置监听器
adapter.setListener(new OnRecyclerViewItemClickListener() {
@Override
public void onClick(View view, int position) {
Toast.makeText(getApplicationContext(), items.get(position).getTitle(), Toast.LENGTH_LONG).show();
}
});
//设置适配器
recyclerView.setAdapter(adapter);
//默认动画效果
recyclerView.setItemAnimator(new DefaultItemAnimator());
//设置布局管理器,第三个参数为是否逆向布局
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//设置每一项的装饰,这里给它加入分隔线
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
Paint paint = new Paint();
@Override
public void onDraw(Canvas c, RecyclerView parent,
RecyclerView.State state) {
super.onDraw(c, parent, state);
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent,
RecyclerView.State state) {
super.onDrawOver(c, parent, state);
paint.setColor(Color.LTGRAY);
for (int i = 0, size = parent.getChildCount(); i < size; i++) {
View child = parent.getChildAt(i);
c.drawLine(child.getLeft(), child.getBottom(),
child.getRight(), child.getBottom(), paint);
}
}
});
//可以提高效率
recyclerView.setHasFixedSize(true);
}
private void initDatas() {
Item item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
item = new Item();
item.setImg(R.drawable.icon);
item.setTitle("微信支付");
item.setDescription("微信支付:支付成功通知");
item.setTime("晚上20:35");
items.add(item);
}
}
ItemDecoration也可以使用现成的,但是我没有在android源码里找打它,反而是在github上找到的它,这里贴出源码,其作用就是增加分隔线,支持水平和竖直状态,而我的代码只是简单处理了竖直状态下的分隔线
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
@Override
public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
布局文件
<RelativeLayout 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" >
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
整个使用过程还是相当简单的,这只是这个控件的使用的开始,而它的作用远远不止这些。更多的内容在之后的博文中详细写。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。