Android

RecyclerView的简单使用

2019-02-25  本文已影响7人  12313凯皇
implementation 'com.android.support:recyclerview-v7:26.1.0'
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="hu.yu.com.recyclerviewdemo.MainActivity">

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

item_recycler_view.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="80dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorAccent"
        android:gravity="center"
        android:textColor="@color/colorPrimary" />
</LinearLayout>
public class MyAdaptor extends RecyclerView.Adapter<MyAdaptor.mViewHolder> {

    private List<String> list;

    public MyAdaptor(List<String> list) {
        this.list = list;
    }


    @Override
    public mViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_view, parent, false);
        return new mViewHolder(view);
    }

    @Override
    public void onBindViewHolder(mViewHolder holder, int position) {
        holder.text.setText(list.get(position));
    }

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

    static class mViewHolder extends RecyclerView.ViewHolder {
        TextView text;

        mViewHolder(View itemView) {
            super(itemView);
            this.text = itemView.findViewById(R.id.text);
        }
    }
}

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recycle_view);
        //设置布局方式
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            list.add("item" + i);
        }
        recyclerView.setAdapter(new MyAdaptor(list));
    }
}

如果recyclerview中的item不是都是一样的,可以参考值得深入学习的控件-RecyclerView(入门篇),其核心在于adapter中重写getItemViewType方法。

上一篇下一篇

猜你喜欢

热点阅读