天高任鸟飞,海阔凭鱼跃
recyclerView的最初实现
现在recyclerView的使用越来越广泛,多条目,多布局,局部刷新,动态改变布局,item的拖拽等等,recyclerView的灵活性是listView不能媲美的地方。今天这篇文章先简单的介绍下recyclerView的简单使用。
先看布局中的代码,只有一个recyclerVeiw
<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/id_recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
接下啦看看主程序
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private Fruit[] fruits = {new Fruit("Apple", R.mipmap.apple), new Fruit("Banana", R.mipmap.banana),
new Fruit("Orange", R.mipmap.orange), new Fruit("Watermelon", R.mipmap.watermelon),
new Fruit("Pear", R.mipmap.pear), new Fruit("Grape", R.mipmap.grape),
new Fruit("Pineapple", R.mipmap.pineapple), new Fruit("Strawberry", R.mipmap.strawberry),
new Fruit("Cherry", R.mipmap.cherry), new Fruit("Mango", R.mipmap.mango)};
private List<Fruit> fruitList = new ArrayList<>();
private FruitAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();
intiViews();
GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
mRecyclerView.setLayoutManager(layoutManager);
adapter = new FruitAdapter(fruitList);
mRecyclerView.setAdapter(adapter);
}
private void intiViews() {
mRecyclerView= (RecyclerView) findViewById(R.id.id_recyclerView);
}
private void initFruits() {
fruitList.clear();
for (int i = 0; i < 50; i++) {
Random random = new Random();
int index = random.nextInt(fruits.length);
fruitList.add(fruits[index]);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_add:
adapter.addData(1);
break;
case R.id.action_delete:
adapter.deleteData(1);
break;
case R.id.action_gridview:
mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
break;
case R.id.action_listview:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
break;
case R.id.action_staggered:
startActivity(new Intent(this,StaggeredGridLayoutActivity.class));
break;
case R.id.action_hor_gridview:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5,StaggeredGridLayoutManager.HORIZONTAL));
break;
}
return super.onOptionsItemSelected(item);
}
}
recyclerView这里的初始化方法要注意下,layoutManager有三种,在menu中我将切换布局就是设置不同的layoutManager.
GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
mRecyclerView.setLayoutManager(layoutManager);
这里用到了menu,菜单里面设置了几个方法,增加,删除一个。切换布局等
<menu 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"
tools:context=".MainActivity">
<item
android:id="@+id/action_add"
android:orderInCategory="100"
android:title="Add"
android:icon="@mipmap/ic_menu_add"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_delete"
android:orderInCategory="100"
android:title="Delete"
android:icon="@mipmap/ic_menu_delete"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_listview"
android:orderInCategory="100"
android:title="ListView"
app:showAsAction="never" />
<item
android:id="@+id/action_gridview"
android:orderInCategory="100"
android:title="GridView"
app:showAsAction="never" />
<item
android:id="@+id/action_hor_gridview"
android:orderInCategory="100"
android:title="HorizontalGridView"
app:showAsAction="never" />
<item
android:id="@+id/action_staggered"
android:orderInCategory="100"
android:title="StaggeredGridView"
app:showAsAction="never" />
</menu>
接下来看看Adapter
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private static final String TAG = "FruitAdapter";
private Context mContext;
private List<Fruit> mFruitList;
static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View view) {
super(view);
cardView = (CardView) view;
fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
fruitName = (TextView) view.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> fruitList) {
mFruitList = fruitList;
}
public void addData(int pos) {
mFruitList.add(new Fruit("Apple", R.mipmap.apple));
notifyItemInserted(pos);
}
public void deleteData(int pos) {
mFruitList.remove(pos);
notifyItemRemoved(pos);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mContext == null) {
mContext = parent.getContext();
}
View view = LayoutInflater.from(mContext).inflate(R.layout.fruit_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "点击了", Toast.LENGTH_SHORT).show();
}
});
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Fruit fruit = mFruitList.get(position);
holder.fruitName.setText(fruit.getName());
Glide.with(mContext).load(fruit.getImageId()).into(holder.fruitImage);
}
@Override
public int getItemCount() {
return mFruitList.size();
}
}
注意一下几点即可:
- 继承于RecyclerView.Adapter,里面传一个继承于RecyclerView.ViewHolder的对象,继承该对象后会重写构造方法,一般在这个构造方法里面实现item控件的初始化操作
- 继承RecyclerView.Adapter方法后会实现两个方法
- onCreateViewHolder()该方法返回一个实现了的Viewholder对象,在该方法中初始化布局。
- onBindViewHolder()该方法主要做绑定数据方法
关于实现item的分割线的问题,文档上说
- mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL_LIST));
这里我也将提供DividerItemDecoration类
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* This class is from the v7 samples of the Android SDK. It's not by me!
* <p/>
* See the license above for details.
*/
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; //item间隔图片资源
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)
{
//Log.v("recyclerview - itemdecoration", "onDraw()");
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);
RecyclerView v = new RecyclerView(
parent.getContext());
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);
}
}
}
而我的一般做法是在item 的布局中设置margin或者padding.
好了今天这里介绍recyclerView的简单用法,最后附上gif图一张
参考文献:http://blog.csdn.net/lmj623565791/article/details/45059587