Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView item's X and Y are 0 when clicked

In a RecyclerView, I'm trying to get the clicked item's X and Y position. This is inside my adapter:

@Override
    public void onBindViewHolder(AlfabetoViewHolder holder, final int position) {
       // setImage(holder.imageButton, images.get(position));

        holder.imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.getX(); // This is 0, but it shouldn't be!
                view.getY(); // This is also 0.
                executaSomAnimacaoLetra(sounds.get(position), Utils.getResourceFromFile(popups.get(position), context), view); // I do some stuff here
            }
        });


    }

Thing is, both X an Y always return 0, and they shouldn't. I need the X an Y of the clicked item to do some animations.

I already tried getting the X and Y position inside of an OnGlobalLayoutListener and inside of an OnPreDrawListener (both work when you need the X and Y on the activity's onCreate), but they also return 0.

I'm using the GridLayoutManager on my RecyclerView:

recyclerView.setLayoutManager(new GridLayoutManager(Activity_alfabeto.this, 7, LinearLayoutManager.VERTICAL, false));

Any help is appreciated.

like image 737
Felipe Ribeiro R. Magalhaes Avatar asked Mar 12 '23 07:03

Felipe Ribeiro R. Magalhaes


1 Answers

Got it working. I had to use this approach:

int[] originalPos = new int[2];
view.getLocationInWindow(originalPos);
//originalPos[0] is my X
//originalPos[1] is my Y

Here getX and getY are relative to the view's parent, not their absolute position on the screen.

    view.getLocationOnScreen(originalPos);

Could also be used.

like image 171
Felipe Ribeiro R. Magalhaes Avatar answered Mar 26 '23 14:03

Felipe Ribeiro R. Magalhaes