zoukankan      html  css  js  c++  java
  • RecyclerView基本用法

    1. 在gradle.build的dependencies中添加RecyclerView需要的包

    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.android.support:recyclerview-v7:23.4.0'

    添加完后记得要Sync Gradle

    2. 在布局文件中添加控件RecyclerView. 

    <android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    3.在Activity中找到RecyclerView并设置LayoutManager和Adapter

    RecyclerView rv;
    NewsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rv = (RecyclerView) findViewById(R.id.rv);
    rv.setLayoutManager(new LinearLayoutManager(this));
    rv.setAdapter(adapter);

    }

    4. 写Adapter

    class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.VH> {
    String[] data = {"a","b","c","d","e"};

      //创建ViewHoler
    @Override
    public VH onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item,parent,false);
    VH vh = new VH(view);
    return vh;
    }

      //数据绑定
    @Override
    public void onBindViewHolder(VH holder, int position) {
    holder.title.setText(data[position]);

    }

    @Override
    public int getItemCount() {
    return data.length;
    }

      //内部类VH 保存所有view
    class VH extends RecyclerView.ViewHolder {
    public TextView title;
    public VH(View itemView) {
    super(itemView);
    title = (TextView)itemView.findViewById(R.id.title);
    }
    }


    }
    
    





     
  • 相关阅读:
    除法
    01.python对象
    00.基础入门
    00.斐波那契数列第n项
    16.分治排序
    15.快速排序
    14.插入排序--希尔排序(缩小增量排序)
    13.插入排序--直接插入排序(简单插入排序)
    12.选择排序
    11.冒泡排序
  • 原文地址:https://www.cnblogs.com/yidan621/p/5658938.html
Copyright © 2011-2022 走看看