RecyclerView 控件使用

build.gradle

1
compile 'com.android.support:recyclerview-v7:24.2.1'

Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MainActivity extends AppCompatActivity {
private List<String> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
RecyclerView recyClerView = (RecyclerView) findViewById(R.id.myRecycler);
GridLayoutManager layoutManager = new GridLayoutManager(this, 4); //网格布局
recyClerView.setLayoutManager(layoutManager);
recyClerView.setAdapter(new MyRecycler(list));
}
private void init() {
list.add("13");
list.add("23");
list.add("3");
list.add("fd123");
list.add("1fd3");
list.add("123fa");
list.add("123f");
}
}

RecyclerView.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class MyRecycler extends RecyclerView.Adapter<MyRecycler.ViewHolder>{
List<String> list;
private static final String TAG = "MyRecycler";
public MyRecycler(List<String> list) {
this.list = list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_demo,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final String str = list.get(position);
holder.textView.setText(str);
holder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), str, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return list.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.myText_hello);
}
}
}

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/myRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

recycler_demo.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/myText_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
0%