RecycleView学习计划1

2016-09-02  本文已影响0人  Geepi

代码集成

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);
        }
    }
}
QQ图片20160902103410.png
上一篇下一篇

猜你喜欢

热点阅读