1

I have an ArrayList that has some String variables and I have a custom ArrayAdapter that I populate from the ArrayList. Now when that list in displayed and an item in the list is clicked, I want the program to do something but I don't know how to do it. I looked at a few examples but I didn't understand where exactly to put the code. So here is my code, can you tell me what to do and where to do it?

MainActivity.java

public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> listAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    updateList(listOfItems);
}
public void updateList(ArrayList<String> possibleWords){
    listAdapter = new CustomListAdapter(this, R.layout.custom_list,possibleWords);
    android.R.layout.simple_list_item_1, possibleWords);
    final ListView listView = (ListView)findViewById(R.id.listview);
    listView.setAdapter(listAdapter);
}

CustomListAdapter.java Class

public class CustomListAdapter extends ArrayAdapter {

private Context mContext;
private int id;
private List<String> items ;

public CustomListAdapter(Context context, int textViewResourceId , List<String> list )
{
    super(context, textViewResourceId, list);
    mContext = context;
    id = textViewResourceId;
    items = list ;
}

@Override
public View getView(int position, View v, ViewGroup parent)
{
    View mView = v ;
    if(mView == null){
        LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mView = vi.inflate(id, null);
    }
    return mView;
}
}

Here is a sample image on what the output looks like

Sample output

So when "act" or "cat" are clicked, I want to do something but I don't know how to handle the click and where to put the code on what I want to do.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Parth Bhoiwala
  • 1,282
  • 3
  • 19
  • 44

2 Answers2

1

Put the below code on your main activity

listview.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
              //do your work here
      }
   });
dindinii
  • 645
  • 4
  • 7
-1

Please just add click listener in adapter like as follows

mView.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245