Edit an item in android list view

0 votes
asked Sep 13, 2017 by user8583428

I am new in android development and I have a simple question, I made a ListView with ArrayAdapter and an array of some strings. I want the text of that item (or any other property such text color) will be changed when an item clicked!! I do that by :

private AdapterView.OnItemClickListener MshowforItem = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ((TextView)view).setText("Hello"); }
};

So when I click on any item the text of it will change but when I scroll down/up and then went to that position, the text of that item changed to the default!! what should I do?????

1 Answer

0 votes
answered Mar 15, 2018 by patrick-r

Listview populates from dataset [ String Array ] we provide while creating ArrayAdapter. we must update data of that String Array to persist the change of text.

Code:

 public class listviewActivity extends AppCompatActivity { ListView listView; String dataset[] = {"data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data", "data"}; ArrayAdapter<String> arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); listView = (ListView) findViewById(R.id.listview); arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataset); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(MshowforItem); } private AdapterView.OnItemClickListener MshowforItem = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tvTemp = ((TextView) view); dataset[position] = "Hello"; tvTemp.setText(dataset[position]); arrayAdapter.notifyDataSetChanged(); } }; }
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...