- 老早就听说了recycleView,是google在V7包提供的,以用来替代ListView、gridView的组件。本人以前在IOS4.3的时候,写过ios,对于目前的ListView组件来说,确实可配置的太少,已经无法支撑强大的产品需求和功能,更加无法和ios的tableview抗衡。
- 本次学习计划大致会有几篇文章,从最开始的使用recycleView,以及高阶使用等等。开始会给code,让读者有个初探,后续会对API进行梳理与分析。
代码集成
xml代码
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#ff0000"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/id_num"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="1" />
</FrameLayout>
UI界面代码
/**
* 作者:liaoyong on 2016/7/6 09:54
* 邮箱:liao__yong@163.com
* 描述:
*/
public class RecycleListViewActivity extends Activity {
private RecyclerView mRecyclerView;
private List<String> mDatas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclelistview);
initData();
mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL_LIST));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
RecycleViewAdapter recycleViewAdapter = new RecycleViewAdapter(this, mDatas);
mRecyclerView.setAdapter(recycleViewAdapter);
}
protected void initData()
{
mDatas = new ArrayList<String>();
for (int i = 0; i < 20; i++)
{
mDatas.add(String.format("this is the %d record.", i));
}
}
}
适配器代码
/**
* 作者:liaoyong on 2016/8/29 17:24
* 邮箱:liaoyong@tuliu.com
* 描述:
*/
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {
private Context mContext;
private List<String> mDataSource;
public RecycleViewAdapter(Context context, List<String> dataSource) {
mContext = context;
mDataSource = dataSource;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_home, parent,
false));
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(mDataSource.get(position));
}
@Override
public int getItemCount() {
return mDataSource.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
public MyViewHolder(View view)
{
super(view);
tv = (TextView) view.findViewById(R.id.id_num);
}
}
}
- 以上代码分享结束了,run以下,会如预期的显示出列表。
QQ图片20160902103410.png
- 结束语,recycleView的优越性是显而易见,不过更加强大的功能在这篇博文中还没有体现,这篇只是启蒙,后续几篇会逐渐展现recycleView的强大之处。
网友评论