RecycleView是V7包下的,能夠說是ListView的升級版,由於ListView是不支持橫向滑動,而RecycleView既支持橫向也支持縱向滑動,使用很方便,可是有一點坑爹的就是沒有條目的點擊事件,須要咱們本身來寫ide
首先Activity的佈局以下:
佈局
Item的佈局我只是用一個簡單的TextView來寫的,因此就不傳圖了;this
而後在Activity中的onCreat方法中,獲取到RecyclerView控件,而後設定Layout管理器code
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.rec);繼承
固然這裏的setOrientation也能夠設置爲horizontal的,這樣就是橫向的接口
MyAdaper就是適配器,他要繼承的是RecyclerView.Adaper,主要重寫裏面的onCreatViewHolder(),onBindViewHolder(),getItemCount()這三個方法,事件
onCreatViewHolder()就是建立ViewHolderget
onBindViewHolder()就是綁定ViewHolder,和數據綁定it
getItemCount()就是獲取總的條目數
io
private class MyAdapter extends RecyclerView.Adapter { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.item, null); Holder holder = new Holder(view); return holder; } @Override public void onBindViewHolder( RecyclerView.ViewHolder holder, final int position) { final Holder h = (Holder) holder; h.setData(position); } @Override public int getItemCount() { return list.size(); } } class Holder extends RecyclerView.ViewHolder { TextView mtv; public Holder(View view) { super(view); mtv = (TextView) view.findViewById(R.id.tv); } public void setData(int position) { mtv.setText(list.get(position).getName()); } }
這樣就能夠了,可是有一點就是item沒有條目點擊事件,若是想要用的話,咱們只能本身來寫個接口了,由於個人適配器是寫在Activity中的,也就是和OnCreat()在一個類中,因此以下:
首先在全局中寫個接口
public interface onItemClickListener{ void onItemClick(View vi,int position); }
而後在適配器MyAdapter中
private onItemClickListener mOnItem; public void onItemClickListener(onItemClickListener mOnItemClickListener){ this.mOnItem = mOnItemClickListener; }
而後在onBindViewHolder()方法
@Override public void onBindViewHolder( RecyclerView.ViewHolder holder, final int position) { final Holder h = (Holder) holder; h.setData(position); if(mOnItem != null){ h.mtv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOnItem.onItemClick(h.mtv,position); } }); } }
這就能夠了,用的話在new 出適配器的時候設置點擊事件
MyAdapter myAdapter = new MyAdapter(); myAdapter.onItemClickListener(new onItemClickListener() { @Override public void onItemClick(View vi, int position) { Toast.makeText(Priactise.this, "這是" + position, Toast.LENGTH_SHORT).show(); } }); mRecycle.setAdapter(myAdapter);