android-fragments 片段ListView在传回时加倍

7fhtutme  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(122)

我在一个片段中为我的ListView使用了一个自定义适配器。(ArrayList中的所有内容都被再次添加到listView中)。每次我转到第二个片段并返回时都会发生这种情况(ArrayList再次被追加到后面)我试着检查适配器是否为空,但很明显,当你回到片段时,它总是空的。
我试着把我的代码移到onResume()onStart()函数中,但是这并不能修复我的代码:(
另外,我尝试在onPause中添加arr.clear()notifyAll(),但这只是中断了我的代码(无法转换到第二个片段)。

public void onStart() {
        super.onStart();
        for (int i = 0; i < device_names.length; i++) {
            arr.add(device_names[i]);
        }

        final ListView list = (ListView)getView().findViewById(R.id.list);
        CustomListView customAdapter = new CustomListView(context, arr);
        if (list.getAdapter() == null) {
            Log.i("SAKEGA", String.valueOf(list.getAdapter()));
            Log.i("SAKEGA", "it's null");
        } else {
            Log.i("SAKEGA", "it's not null waaaaaaaaaah");
            list.setAdapter(null);
        }
        list.setAdapter(customAdapter);
        Log.i("SAKEGA", "HMPH");
        Button tv = (Button)getView().findViewById(R.id.add_devices_text);
        ImageButton add = (ImageButton) getView().findViewById(R.id.add);
        tv.setOnClickListener(add_device_click); // this click listener calls the 2nd fragment
        add.setOnClickListener(add_device);
    }

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_scanneractivity, null);
    return root;
}

我想做的是,一旦我们回到片段,我就清除ListView,并使用ArrayList重新填充listView。

14ifxucb

14ifxucb1#

尝试onStart()本身中创建一个空数组列表,就像你在那里写代码一样。你所做的就是保持那个数组,每次你回来的时候,它都会再次加载你的数组,再次创建条目。

相关问题