先来两个布局文件
<?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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RecycleListView" android:layout_margin="10dp" android:textSize="25sp" android:textColor="#000000" android:layout_gravity="center"/> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView> </LinearLayout>
下面是另一个:
<?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="wrap_content"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="25sp" android:textColor="#000000" android:id="@+id/number" android:layout_margin="5dp" android:text="1"/> </LinearLayout>
布局很简单,接下来直接放Activity的代码:
recyclerView = (RecyclerView) findViewById(R.id.recyclerView); List<String>strings = new ArrayList<>(); for (int i = 0; i < 15; i++) { strings.add(""+i); } LinearLayoutManager manager = new LinearLayoutManager(this);//很重要 manager.setOrientation(LinearLayoutManager.HORIZONTAL);//控制横竖滑动 recyclerView.setLayoutManager(manager);//加载进Layout recyclerView.setAdapter(new MyAdapter(context,strings));
最后是自定义Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { Context context; List<String> strings; public MyAdapter(Context context, List<String> strings) { this.context = context; this.strings = strings; } static class ViewHolder extends RecyclerView.ViewHolder{ private TextView number; public ViewHolder (View view){ super(view); number = (TextView) view.findViewById(R.id.number); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler,parent,false); final ViewHolder vie = new ViewHolder(view); vie.number.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = vie.getAdapterPosition(); Toast.makeText(context, ""+strings.get(position), Toast.LENGTH_SHORT).show(); } }); return vie; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.number.setText(strings.get(position)+""); } @Override public int getItemCount() { return strings.size(); } }
就这样。