你可以把RecyclerView其实就类似于ListView(区别在于:它是没有横线在文字下方的)
其效果图如下:
XML代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <android.support.v7.widget.RecyclerView
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/rv_main_list"></android.support.v7.widget.RecyclerView>
- </LinearLayout>
Java代码如下:
- public class MainActivity extends AppCompatActivity {
- private RecyclerView rv_main_list;
- private String[] names;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- rv_main_list = (RecyclerView) findViewById(R.id.rv_main_list);
- names = new String[]{"没没","又有","花花","球球","哦哦","提提"};
- //rv_main_list既可以横着也可以竖着
- rv_main_list.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
- rv_main_list.setAdapter(new MyAdapter());
- }
- class MyAdapter extends RecyclerView.Adapter{
- class MyViewHolder extends RecyclerView.ViewHolder{
- public TextView textView;
- public MyViewHolder(View itemView) {
- super(itemView);
- textView= (TextView) itemView.findViewById(android.R.id.text1);
- }
- }
- //类似BaseAdapter中的getView的方法
- //ViewHolder类似BaseAdapter中的ItemTag
- @Override
- public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- //解析布局文件
- View v= getLayoutInflater().inflate(android.R.layout.simple_list_item_1,null);
- return new MyViewHolder(v);
- }
- //绑定值
- @Override
- public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
- MyViewHolder myViewHolder= (MyViewHolder) holder;
- myViewHolder.textView.setText(names[position]);
- }
- @Override
- public int getItemCount() {
- return names.length;
- }
- }
- }