RecyclerView 和 ViewHolder
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RecyclerView 和 ViewHolder相关的知识,希望对你有一定的参考价值。
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setActionBar(toolbar); final SwipeRefreshLayout srl = (SwipeRefreshLayout) findViewById(R.id.srl); srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { srl.postDelayed(new Runnable() { @Override public void run() { srl.setRefreshing(false); } },3000); } }); srl.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,LinearLayoutManager.VERTICAL); //layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(new Myadapter()); } private class Myadapter extends RecyclerView.Adapter<Myadapter.ListHoldewer>{ //设置条目 @Override public ListHoldewer onCreateViewHolder(ViewGroup parent, int viewType) { //TextView textview = new TextView(MainActivity.this); View view = View.inflate(MainActivity.this, R.layout.aaaa, null); return new ListHoldewer(view); } //获取条目数据 @Override public void onBindViewHolder(ListHoldewer holder, int position) { holder.setData(position); } //获取条目个数 @Override public int getItemCount() { return 100; } class ListHoldewer extends RecyclerView.ViewHolder{ TextView textview1; TextView textview2; View mitemView; public ListHoldewer(View itemView) { super(itemView); mitemView = itemView; textview1 = (TextView) itemView.findViewById(R.id.text1); textview2 = (TextView) itemView.findViewById(R.id.text2); } public void setData(int position) { textview1.setText("当前的位置:"+position); textview2.setText("当前显示的文本"); mitemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,textview1.getText(),Toast.LENGTH_LONG).show(); } }); } } } }
以上是关于RecyclerView 和 ViewHolder的主要内容,如果未能解决你的问题,请参考以下文章
Android踩坑日记:RecyclerView中EditText和ImageView的ViewHolder复用坑
Android踩坑日记:RecyclerView中EditText和ImageView的ViewHolder复用坑
RecyclerView中ViewHolder重用机制理解(解决图片错乱和闪烁问题)
RecyclerView中ViewHolder重用机制理解(解决图片错乱和闪烁问题)