Search code examples
androidlistviewtextandroid-arrayadapteronitemclicklistener

Change text of a listview, that is filled by an ArrayAdapter


Is there any way to change the text in a listview, which is filled by an ArrayAdapter?

My array:

public String[] trainingstage = {"Hello", "Hello 2"};

The ArrayAdapter

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,

android.R.layout.simple_list_item_1, trainingstage);

setListAdapter(adapter);

ListView listView = getListView();

listView.setOnItemClickListener(this);

OnItem:

public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        switch (position) {
        //untrained
        case 0: 
         //here the text in the listview should change from "Hello" to "BYE"

        case 1:
        //here the text in the listview should change from "Hello 2" to "BYE 2" 
  }

Thanks for help!


Solution

  • You can achieve what you want like this:

    public void onItemClick(AdapterView<?> parent, View view, int position,
              long id) {
    
          TextView tv = (TextView)view.findViewById(android.R.id.text1);
    
          switch (position) {
          //untrained
          case 0: 
           //here the text in the listview should change from "Hello" to "BYE"
              tv.setText("BYE");
              break;
    
          case 1:
          //here the text in the listview should change from "Hello 2" to "BYE 2" 
              tv.setText("BYE 2");
              break;
          }
      }
    

    What is android.R.id.text1

    • ArrayAdapters constructor uses android.R.layout.simple_list_item_1 xml layout as its second parameter and this layout has one child - TextView with ID android.R.id.text1.