您的位置:首页 > 移动开发 > Android开发

RecyclerView和cardView的初次体验

2016-12-23 18:19 253 查看
第一 引入库依赖

25代表当前编译版本,根据需求改正

compile ‘com.android.support:design:25.0.1’

compile ‘com.android.support:cardview-v7:25.0.+’

布局xml使用

<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>


adapter的布局 list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">

<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:padding="10dp"/>
</android.support.v7.widget.CardView>
</LinearLayout>


编写adapter

public class MyAdapter extends RecyclerView.Adapter<ViewHolder> {

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//最上面获取view,子布局显示不全
//View view = View.inflate(MainActivity.this, R.layout.list_item, null);
//View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item,null);
View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTv.setText(alst.get(position));
}

@Override
public int getItemCount() {
return alst.size();
}
}

public class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTv;

public ViewHolder(View itemView) {
super(itemView);
mTv = (TextView) itemView.findViewById(R.id.tv);
}
}


代码中使用

public class MainActivity extends Activity {

private ArrayList<String> alst;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alst = new ArrayList<>();
alst.add("这两个包好像都是的,,");
alst.add("放我们日常用到的控件");
alst.add("但是有些是在view包中");
alst.add("有些是在widget包中");
alst.add("放我们日常用到的控件");
alst.add("有些是在widget包中");
alst.add("这两个包好像都是的");
RecyclerView mRv = (RecyclerView) findViewById(R.id.rv);
mRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mRv.setAdapter(new MyAdapter());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android