简体   繁体   中英

How do I change a list item text for a ListFragment/ArrayAdapter?

I have a fragment which extends ListFragment.

In it I use an ArrayAdapter

public class MyFragment extends ListFragment {
    public void onStart() {
        super.onStart();
        List<String> list = new ArrayList<String>();
        list.add("Superman");
        list.add("Batman");
        arrayAdapter = new ArrayAdapter<OptionToStringAdapter>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                list);
        getListView().setAdapter(arrayAdapter);
        getListView().setOnItemClickListener(new ModifyOption(this));
        setListShown(true);
    }

When the user taps an item I want to modify the text.

How do I modify the text?

public class ModifyOption implements OnItemClickListener {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ???What goes here????
    }
}

try with below code:

public class ModifyOption implements OnItemClickListener { public void onItemClick(AdapterView parent, View view, int position, long id) {

arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.insert("new text",position);

 } }

Assuming you want to change the content of the list item you clicked.

First, change the value using a dialog or widget of your choice. Second, change the value of the item at the position in the list by using 'position' argument.

Third, call notifyDataSetChanged() method of the adapter object.

public class ModifyOption implements OnItemClickListener {
    public void onItemClick(AdapterView parent, View view, int position, long id) {


       // create a dialog or other widget
       String newValue = "your_new_value";
       list.set(position,newValue);  
       arrayAdapter.notifyDataSetChanged();  //informs views that data has been changed


    }
}

This seems to do the trick. I don't know if this is an appropriate way though.

public void onItemClick(AdapterView parent, View view, int position, long id) { TextView textview = (TextView) view.findViewById(android.R.id.text1); textview.setText("Spiderman"); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM