Search code examples
javaandroidandroid-listviewonclick

Implement onClick listener in Listview adapter class


I have a Activity which shows json that has objects set as name and link. Name is displayed to the user by using getName(). Now I want to implement the onClicklistener such that new activity will open based on the position and equivalent url i.e getLink() of same position and sent it to next activity as extras.

Here is my listview adapter

public class ListViewAdapter extends ArrayAdapter<Hero> {

    //the hero list that will be displayed
    private List<Hero> heroList;

    //the context object
    private Context mCtx;

    //here we are getting the herolist and context
    //so while creating the object of this adapter class we need to give herolist and context
    public ListViewAdapter(List<Hero> heroList, Context mCtx) {
        super(mCtx, R.layout.vault_list, heroList);
        this.heroList = heroList;
        this.mCtx = mCtx;
    }

    //this method will return the list item
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //getting the layoutinflater
        LayoutInflater inflater = LayoutInflater.from(mCtx);

        //creating a view with our xml layout
        View listViewItem = inflater.inflate(R.layout.vault_list, null, true);

        //getting text views
        Button btn_one = listViewItem.findViewById(R.id.btn_one);
     

        //Getting the hero for the specified position
        Hero hero = heroList.get(position);

        //setting hero values to textviews
        btn_one.setText(hero.getName());
       

        //returning the listitem
        return listViewItem;
    }


Solution

  • If I understand you correctly, you want to let use click on item of your listview and go to next activity with the related link。You can implement the onItemclick method to achieve your function.