Skip to content Skip to sidebar Skip to footer

Listview Replaces First Item Instead Of Creating New Items

I am trying to add String items to my ListView using Fragments. I have four Buttons. Each time a Button is clicked, the ListView should add a String item: 'Button 1,2,3, or 4 click

Solution 1:

Everytime you call changeText() your adapter is reset so only one item will be displayed

Change your fragment like this

publicclassListViewFragment1extendsFragment {

protectedArrayAdapter<String> adapter1;
ListView list1;

@OverridepublicViewonCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.list_view_fragment1, container, false);       
    adapter1 = newArrayAdapter<String>(getActivity(), R.layout.items);
    list1 = (ListView) view.findViewById(R.id.listview1);
    list1.setAdapter(adapter1);
    return view;
}

publicvoidchangeText(String data){
    adapter1.add(data);
    adapter1.notifyDataSetChanged();
}
}

Post a Comment for "Listview Replaces First Item Instead Of Creating New Items"