简体   繁体   中英

How can I manage onClick function from my custom listview adapter in main activity class

I've created a custom adapter for a class that have a button . In this code I used onClick function in adapter class but I don't want this . I want to call it from main activity class (Like listview.setOnItemClickListener). How can I do that ? Notice that I want be able to get position of button or contact properties

public View getView(int position,View convertView,ViewGroup parent) {

    Contact contact = contacts.get(position);
    final ViewHolder holder ;
    if (convertView == null){
        holder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(context) ;
        convertView = inflater.inflate(resource,parent,false);
        holder.btnCall = convertView.findViewById(R.id.btnCall);
        holder.imgAvatar = convertView.findViewById(R.id.imgAvatar);
        holder.txtName = convertView.findViewById(R.id.txtName);
        holder.txtPhoneNumber = convertView.findViewById(R.id.txtPhoneNumber);
        convertView.setTag(holder);
    }else {
        holder = (ViewHolder)convertView.getTag();
    }
    holder.txtPhoneNumber.setText(contact.getContactNumber());
    holder.txtName.setText(contact.getContactName());
    int imageId = contact.getGender() == 0 ? R.drawable.male : R.drawable.female;
    holder.imgAvatar.setImageResource(imageId);
    holder.btnCall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, holder.txtName.getText().toString() + " "
                    + holder.txtPhoneNumber.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    });
    return convertView ;

}

private class ViewHolder{

    public ImageView imgAvatar ;
    public TextView txtPhoneNumber ;
    public TextView txtName ;
    public Button btnCall ;
}

You can set onItemClickListener in main class after setting the adapter like the example given below:

  listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, final View view,
                int position, long id) {
        final String item =(String)parent.getItemAtPosition(position);
        list.remove(item);
        adapter.notifyDataSetChanged();
        }

    });

将onClickListener添加到ListAdapter的getView()中的Button中。

您可以创建一个带有要传递的数据参数的方法的接口,然后将该接口传递给适配器并在活动中实现该接口

Remove on click listener from adapter and set listview on click listener. Get data from contact array from on click position.

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