首页 > 解决方案 > 使用 ArrayAdapter 意味着不再使用循环?

问题描述

因此,我最近研究了 ArrayAdapter 和 ListView,但是当我不同时使用这两者但使用 LinearLayout 时,我正在放置一个 for 循环,但是当我使用 ListView 时,代码完全不同,看起来我不再使用 for 循环了。我想知道 ListView 不需要循环吗?如果数据存储在 Arraylist 中?

案例一:使用线性布局

ArrayList<String> words= new ArrayList<String>();

words.add(0, "one");
words.add(1, "two");
words.add(2, "three");
words.add(3, "four")


LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);


for (int index= 0; index < 3; index++) {
                /*TextView wordView = new TextView(this);
                wordView.setText(words.get(index));
                rootView.addView(wordView);


Case 2: When using  listview + arrayadapter 

ArrayList<String> words= new ArrayList<String>();

words.add(0, "one");
words.add(1, "two");
words.add(2, "three");
words.add(3, "four");


ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words);

ListView listView = (ListView) findViewById(R.id.list);

listView.setAdapter(itemsAdapter);

所以想知道为什么ArrayAdapter和ListView中没有循环语句。

标签: arraysfor-looplistviewarraylistandroid-arrayadapter

解决方案


(ListView 的)适配器从数据对象(在本例中为 ArrayList)中提取正确的数据,并将这些数据分配给ListView

适配器管理数据模型并使其适应小部件中的各个条目。适配器扩展了 BaseAdapter 类。

有关更多信息,您可以查看此处:https ://www.vogella.com/tutorials/AndroidListView/article.html 或官方 Android 文档:https ://developer.android.com/reference/android/widget/ListView


推荐阅读