简体   繁体   English

ListView 适配器在添加项目时的工作

[英]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 开发的新手,对setAdapterListView的工作有疑问。

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()的打印语句放入CustomAdaptergetView(..)方法来进行交叉检查。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM