添加新项目时删除ListView xml条目

时间:2015-02-05 18:27:10

标签: android xml listview adapter

我使用xml中的条目将项添加到ListView。但由于某些原因,当我动态地向ListView添加项目时,条目项将被删除。

有人可以解释一下原因吗?

代码:

list_view_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:entries="@array/listview_array"
    android:id="@+id/listview1">
</ListView>

ListViewFragment.java

public class ListViewFragment1 extends Fragment {

    protected ArrayAdapter<String> adapter1;

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {       

        return inflater.inflate(R.layout.list_view_fragment, container, false);
    }

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

        adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.items);     
    }

    public void changeText(String data){
        ListView list1 = (ListView) getActivity().findViewById(R.id.listview1);
        list1.setAdapter(adapter1);
        adapter1.add(data);
        adapter1.notifyDataSetChanged();
    }   
}

我认为当我使用changeText(String data)动态添加项目时,我创建了一个新的ListView,它会从xml中删除所有条目。

有人可以帮忙吗? - 如何保存我的参赛作品?

1 个答案:

答案 0 :(得分:0)

尝试更改此

public void changeText(String data){
    ListView list1 = (ListView) getActivity().findViewById(R.id.listview1);
    list1.setAdapter(adapter1);
    adapter1.add(data);
    adapter1.notifyDataSetChanged();
}  

到这个

public void changeText(String data){
    adapter1.add(data);
    adapter1.notifyDataSetChanged();
}  

将您的onCreateView更改为

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){       

    adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.items);  
    ListView list1 = (ListView) getActivity().findViewById(R.id.listview1);
    list1.setAdapter(adapter1); 
    return inflater.inflate(R.layout.list_view_fragment, container, false);
}

代码未经测试。如果它不起作用,请告诉我。