一直以来都是用ListView和GridView来做列表开发,懒得去学RecyclerView,因为在功能上没有太大的差异,就按习惯去开发了。
最近闲着,正好学一下RecyclerView,改变开发习惯,用得好的话以后就都用RecyclerView了。先从最简单的RecyclerView做起。
首先在gradle里添加依赖:
implementation 'com.android.support:recyclerview-v7:28.0.0'
在布局文件中加入它:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/testRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
item的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="80dp"
android:layout_height="80dp"
android:gravity="center">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/testtxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123"/>
</LinearLayout>
继承RecyclerView.Adapter的Adapter:
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestHolder> {
private Context context;
private List<String> testlist;
public TestAdapter(Context context,List<String> testlist){
this.context = context;
this.testlist = testlist;
}
@Override
public TestHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_test, viewGroup, false);
return new TestHolder(view);
}
@Override
public void onBindViewHolder(TestHolder testHolder, final int i) {
testHolder.textView.setText(testlist.get(i));
testHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,testlist.get(i),Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return testlist.size();
}
public class TestHolder extends RecyclerView.ViewHolder {
public TextView textView;
public TestHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.testtxt);
}
}
}
Activity:
public class TestActivity extends Activity {
private RecyclerView testRecycler;
private TestAdapter testAdapter;
private List<String> testlist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
init();
}
private void init() {
testRecycler = (RecyclerView) findViewById(R.id.testRecycler);
testRecycler.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
testlist = new ArrayList<>();
testlist.add("test1");
testlist.add("test2");
testlist.add("test3");
testlist.add("test4");
testAdapter = new TestAdapter(this,testlist);
testRecycler.setAdapter(testAdapter);
}
}