Search code examples
androidontouchlistenerlayout-inflater

Get index position of element inside a inflated view


I am trying to get the index of a spinner that is inside my inflated view.

Although I'm successful in retrieving the index of my child view when it's inflated on a button click like this:

itineraryDetailLL = (LinearLayout) findViewById(R.id.itineraryDetailLinearlayout);
childView = getLayoutInflater().inflate(R.layout.cardview, null);
itineraryDetailLL.addView(childView);

int posValue = itineraryDetailLL.indexOfChild(childView);
Toast.makeText ( PlanItineraryDetailView.this, Integer.toString(posValue), Toast.LENGTH_SHORT ).show();

This bit of code returns me 0 for 1st inflated view, 1 for 2nd inflated view and so on...

Problem

But when I'm trying to get the index position of the spinner (by calling the setOnTouchListener event) in each of my child view it returns me the last index position for each spinner

spinnerPlanItinerary.setOnTouchListener(new View.OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int indexValueTown = itineraryDetailLL.indexOfChild(childView);
            Toast.makeText ( PlanItineraryDetailView.this, Integer.toString(indexValueTown), Toast.LENGTH_SHORT ).show();
            return true;
        }

    });

This returns me 1 for spinner in my 1st inflated view, 1 for spinner my 2nd inflated view (It should return 0 for spinner in my 1st inflated view, 1 for spinner in my 2nd inflated view).

I hope I'm clear with my problem.

Note I'm inflating only two views only for testing right now.


Solution

  • Posting as answer so someone who stumble here might get solution.

    The problem in your case was your itineraryDetailLL & childView were global variables. That means whenever you add new item via button click, there value was updating to the last inflated view. now whenever you touch on Spinner, you were getting the last index as expected.

    So making them local & final variable made sure that you refer to the same view when you touch the spinner.

    I didn't understood your requirement or what you were trying to do fully though. There might be better way of achieving this.