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

时间:2015-07-16 20:58:38

标签: android android-listfragment android-dialogfragment

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

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) {
        ...
        }

    }    
}

1 个答案:

答案 0 :(得分:1)

这就是您的问题所在:

<a href="tel:+17027613327" target="_blank">
    <font color="blue">
       <strong>702-761-3327</strong>
    </font>
</a>

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

也许换行有点澄清了这个问题:

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

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

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

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