Android开发笔记之 RecyclerView和ScrollView嵌套使用,ListView和ScrollView嵌套使用对比
程序员文章站
2022-12-25 15:14:43
直接上代码:
1、activity的代码:
public class mainactivity extends appcompatactivity {
private list lis...
直接上代码:
1、activity的代码:
public class mainactivity extends appcompatactivity { private list list; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); list = new arraylist<>(); for (int i = 0; i < 20; i++) { list.add("item:" + i); } listview listview = findviewbyid(r.id.listview); listview.setadapter(new mylistviewadapter(this, list)); recyclerview recyclerview = findviewbyid(r.id.recyclerview); recyclerview.setadapter(new myadapter(this, list)); linearlayoutmanager manager = new linearlayoutmanager(this, linearlayoutmanager.vertical, false); recyclerview.setlayoutmanager(manager); } }
2、activity中加载的view的布局:
3、recyclerview的adapter:
public class myrecyclerviewadapter extends recyclerview.adapter { private context context; private list list; public myrecyclerviewadapter(context context, list list) { this.context = context; this.list = list; } @override public myviewholder oncreateviewholder(viewgroup parent, int viewtype) { view view = layoutinflater.from(context).inflate(r.layout.item, null); return new myviewholder(view); } @override public void onbindviewholder(myviewholder holder, int position) { holder.title.settext(list.get(position)); } @override public int getitemcount() { return list.size(); } class myviewholder extends recyclerview.viewholder { private textview title; public myviewholder(view itemview) { super(itemview); title = itemview.findviewbyid(r.id.title); } } }
4、运行效果:
结论:6.0模拟器上recyclerview的数据显示完全,并且recyclerview也可以滑动,额、、、模拟器上操作起来稍稍有点卡顿的意思。oppo r9 android5.1真机上,recyclerview数据显示完全,recyclerview失去滑动能力。
下面演示scrollview里嵌套使用listview,adapter的代码如下:
public class mylistviewadapter extends baseadapter { private context context; private list list; public mylistviewadapter(context context, list list) { this.context = context; this.list = list; } @override public int getcount() { return list.size(); } @override public object getitem(int position) { return list.get(position); } @override public long getitemid(int position) { return position; } @override public view getview(int position, view convertview, viewgroup parent) { myviewholder myviewholder = null; if (convertview == null) { convertview = layoutinflater.from(context).inflate(r.layout.item, null); myviewholder = new myviewholder(); convertview.settag(myviewholder); } else { myviewholder = (myviewholder) convertview.gettag(); } myviewholder.title = (textview) convertview.findviewbyid(r.id.title); myviewholder.title.settext(list.get(position)); return convertview; } class myviewholder { textview title; } }
接下来在布局文件中设置recyclerview隐藏,listview设置为显示,运行效果如下:
结论:6.0模拟器上listview数据显示不全,listview可以滑动,oppo r9 android5.1真机上,listview数据显示不全,listview可以滑动。