Search code examples
javaandroidandroid-fragmentsandroid-listviewandroid-dialog

SetOnClickListener doesn't work in DialogFragment


I am trying to get the index when I click in the listview inside the DialogFragment, but I don't get anything... I don't know why...

This is the OnCreatedDialog where I have the setOnClickListener:

This is my Adapter, I am trying to put the setOnClickListener here:

public class AdapterListviewChangeStartingKarateka extends ArrayAdapter {


    Context context;
    int item_Layaut;
    ArrayList<Karateka> data;
    ApiUtils apiUtils;

    public AdapterListviewChangeStartingKarateka(Context context, int item_Layaut, ArrayList<Karateka> data) {
        super(context, item_Layaut,data);
        this.context = context;
        this.item_Layaut = item_Layaut;
        this.data = data;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(item_Layaut, parent, false);
        }
        String image = data.get(position).getPhoto_karateka();

        ImageView elementImage = convertView.findViewById(R.id.change_starting_picture_karateka);
        if(image!= null || !!!image.isEmpty() ) {
            Picasso.get().load(apiUtils.BASE_URL_PICTURE + image).fit().into(elementImage);
        }else{ elementImage.setImageResource(R.drawable.default_image); }

        Button buttonToChange= convertView.findViewById(R.id.item_button_to_change);

        ListView list = convertView.findViewById(R.id.starting_listview);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.d("indexListview", String.valueOf(i));
            }
        });
}

Solution

  • Try to implement an ListView adapter and define your listener in adapter's getView() method.

    You should set listener for each view element.

    viewKarateka.setOnClickListener(new View.OnClickListener() {
       public void onClick(final View v) {
          Log.d("indexListview", String.valueOf(i));
       }
    }