在android.support.v7中提供了RecyclerView这个新组件来替代传统的ListView
RecyclerView通过导入support-v7来使用
使用方法:
android studio下,在项目处右击-open module settings-dependencies-搜索recyclerView启用即可
RecyclerView使用分两部:第一步选择布局类型,setLayoutManager,第二部加载适配器,setAdapt
代码示例
1.MainActivity
package com.example.kanzaki.recycleview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//定义一个RecyclerView
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerView = new RecyclerView(MainActivity.this);
//使用RecycletView作为主布局
setContentView(recyclerView);
//设置布局,这里使用竖形
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//填充内容
recyclerView.setAdapter(new RecyclerView.Adapter() {
//此处创建了一个ViewHolder,可以通过自定义一个ViewHolder,
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(new TextView(parent.getContext()));
}
//填充控件
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//通过MyViewHolder来调用控件
MyViewHolder myViewHolder = (MyViewHolder) holder;
myViewHolder.getTextView().setText(args[position]);
}
//设置RecyclerView子对象数量
@Override
public int getItemCount() {
return args.length;
}
//设置数据源
private String[] args={"Martin","Seven","Lee"};
});
}
}
2.MyViewHolder
package com.example.kanzaki.recycleview;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Kanzaki on 2016/3/21.
*/
public class MyViewHolder extends RecyclerView.ViewHolder {
//自定义ViewHolder,内部包裹一个TextView的控件
private TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView;
}
//创建一个方法使外界能够访问TextView
public TextView getTextView() {
return textView;
}
}