[英]Working of ListView Adapter on Adding Item
I am new to the android development and have got a doubt about the working of setAdapter
and ListView
.我是 android 开发的新手,对
setAdapter
和ListView
的工作有疑问。
My MainActivity.java
looks like below:我的
MainActivity.java
如下所示:
public class MainActivity extends AppCompatActivity {
private Button generate_btn;
private ArrayList<Integer> arr;
private Random rand_generator;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
arr = new ArrayList<Integer>();
setContentView(R.layout.activity_main);
for(int i = 0; i < 5; i++){
arr.add(i);
}
generate_btn = findViewById(R.id.button);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_list_item_1, arr);
listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
for(int i = 0; i < 5; i++){
arr.add(i + 100);
}
As we can see above that I have two for loops, the first one adds integers till 5 to the ArrayList<Integer> arr
and then I am calling the setAdapter
on the listView
.正如我们在上面看到的,我有两个 for 循环,第一个将整数添加到 5 到
ArrayList<Integer> arr
然后我在listView
上调用setAdapter
。 Till here arr
only contains the integers till 5.直到这里
arr
只包含直到 5 的整数。
In the second loop, I am adding integers from 100 to 104 but not calling notifyDataSetChanged()
.在第二个循环中,我添加了从 100 到 104 的整数,但没有调用
notifyDataSetChanged()
。
I expected that the rendered result will contain TextViews
till 5 only since I have set the adapter when arr
was having elements till 5. But to my surprise, the result was having TextViews
of integers added in the second for loop also.我预计渲染结果将仅包含
TextViews
直到 5,因为我在arr
有元素直到 5 时设置了适配器。但令我惊讶的是,结果是在第二个 for 循环中添加了整数的TextViews
。
What am I missing here?我在这里想念什么?
Adapter
maintains the reference to arr
. Adapter
维护对arr
的引用。 So even if we are updating the ArrayList
after the setAdapter(..)
the size is getting updated accordingly and it can be cross-checked by putting a print statement of arr.size()
in getView(..)
method of a CustomAdapter
.因此,即使我们在
setAdapter(..)
之后更新ArrayList
,大小也会相应更新,并且可以通过将arr.size()
的打印语句放入CustomAdapter
的getView(..)
方法来进行交叉检查。
getView(..)
is called by listView
in various cases till adapter.getItemCount()
is more than the internal integer pointer. getView(..)
在各种情况下由listView
调用,直到adapter.getItemCount()
超过内部整数指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.