ListFragment 中的数据如果每次重新打开时多次添加

Data in ListFragment if added multiple time every time it re-opened

我在 DialogFragment 中有一个 ListFragment,我正在将列表数据从 Activity->DialogFragment->ListFragment 传递到 ListFragment。问题是每次我从 Activity 的同一实例打开对话框时都会显示列表,列表数据附加到先前绘制的列表中。这是我正在使用的代码的快照。

class TestActivity extends FragmentActivity {

public void onButtonClick() {
    TestDialogFragment.newInstance(data).show(getSupportFragmentManager(), null);
    }
}

class TestDialogFragment extends DialogFragment {

    Data data;

    public static TestDialogFragment newInstance(Data data) {
        final TestDialogFragment fragment = new TestDialogFragment();
        // add input to fragment argument
        return fragment;
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        final View dialogView = inflater.inflate(R.layout.fragment_test_dialog, container, false);
        // read data from fragment argument
        return dialogView;
    }

    @Override
    public void onActivityCreated(final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final Fragment fragment = TestListFragment.newInstance(testList);
        final FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.chapter_list, fragment).commit();
    }    

    static ArrayList<String> testList = new ArrayList<>();
    {
        testList.add("Test 1");
        testList.add("Test 2");
    }

}

class TestListFragment extends ListFragment {
    public static ChapterListFragment newInstance(final ArrayList<String> testList) {
        final TestListFragment fragment = new TestListFragment();
        // add input to fragment argument
        return fragment;
    }

    @Override
    public void onActivityCreated(final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // read data from fragment argument
        setListAdapter(new TestListAdapter(testList));
    }   


    class ChapterListAdapter extends ArrayAdapter<String> {

        public ChapterListAdapter(final ArrayList<String> testList) {
            super(getActivity(), R.layout.view_test_list_item, testList);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        ...
        }

    }    
}

这是你的问题所在:

static ArrayList<String> testList = new ArrayList<>();
{
    testList.add("Test 1");
    testList.add("Test 2");
}

您的 testList 是静态的,因此在加载 class 时初始化一次。您将项目添加到非静态初始化程序块中,并且每次实例化 class 的新实例时都会执行这些项目。

也许换行符可以稍微说明这个问题:

static ArrayList<String> testList = new ArrayList<>();

{
        testList.add("Test 1");
        testList.add("Test 2");
}

如果您将初始化程序块设为静态,则项目只会添加一次。

static ArrayList<String> testList = new ArrayList<>();
static {
    testList.add("Test 1");
    testList.add("Test 2");
}