recyclerView的使用
1.xml布局
<android.support.v7.widget.RecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView>
2。在Activity中使用
package com.hyang.administrator.studentproject.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.ArrayAdapter; import com.hyang.administrator.studentproject.MyAdapter; import com.hyang.administrator.studentproject.R; import org.xutils.x; import java.util.ArrayList; /** * listView的下拉刷新 */ public class PullListViewActivity extends AppCompatActivity { private ArrayAdapter<String> arrayAdapter; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pull_list_view); x.view().inject(this); initData(); initView(); } private void initData() { mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mAdapter = new MyAdapter(getData()); } private void initView() { mRecyclerView = (RecyclerView) findViewById(R.id.recycler); // 设置布局管理器 mRecyclerView.setLayoutManager(mLayoutManager); // 设置adapter mRecyclerView.setAdapter(mAdapter); } private ArrayList<String> getData() { ArrayList<String> data = new ArrayList<>(); String temp = " item"; for(int i = 0; i < 20; i++) { data.add(i + temp); } return data; } }
3.适配器
package com.hyang.administrator.studentproject; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; /** * Created by Administrator on 2017/6/27. * */ public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private ArrayList<String> mData; public MyAdapter(ArrayList<String> data) { this.mData = data; } public void updateData(ArrayList<String> data) { this.mData = data; notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // 实例化展示的view View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item, parent, false); // 实例化viewholder ViewHolder viewHolder = new ViewHolder(v); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { // 绑定数据 holder.mTv.setText(mData.get(position)); } @Override public int getItemCount() { return mData == null ? 0 : mData.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { TextView mTv; public ViewHolder(View itemView) { super(itemView); mTv = (TextView) itemView.findViewById(R.id.item_tv); } } }