Search code examples
javaandroidgridviewadapter

Get click event from gridview's child item in main activity from adapter


I have a GridView in my activity. I am having 2 elements in the GridView. One is an ImageView and the other is a TextView.

I want to perform an action when clicking the ImageView only, but I want this to happen in the activity and not in the GridView adapter.

I handle the ImageView click in the getView() of my adapter, but I do not want it that way. I want to handle it in the activity when calling:

GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this, items));

gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

        //THIS WORKS FINE
        String string = ((TextView) v.findViewById(R.id.text)).getText().toString();
        Log.d("string",string);

        //THE PROBLEM OCCURS HERE
        ImageView capture = (ImageView) v.findViewById(R.id.capture);
        capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }
});

//THE PROBLEM OCCURS HERE

The action is supposed to happen the first time I click the ImageView, but it only happens on the second click and further.

This is where I am stuck with the issue. I want this action to occur on the first click and not on the second click.


Solution

  • You can see the code block-

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    
        String string = ((TextView) v.findViewById(R.id.text)).getText().toString();
        Log.d("string",string);
    
        //THE PROBLEM OCCURS HERE
        ImageView capture = (ImageView) v.findViewById(R.id.capture);
        capture.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                }
            });
    }
    

    Your imageview capture is adding any action after gridview is being clicked. So, after clicking first time it is executing and then setting click listener to imageview and then next click its executing its onClick block. So better, handle imageview click event inside adapter.

    You can call method inside your activity from adapter class but you should implement setOnClickListener inside your adapter class.