Search code examples
androidandroid-layouttextviewandroid-viewpagerfindviewbyid

Multiple TextViews with same ID/ tag


I have a ViewPager that slides through multiple full screen photos. Each photo has a caption which is an ImageView merged with TextView. I'm trying to hide/ show the TextView caption on the photo based on click action.

Problem: currently I'm using findViewById() to find the TextView within each page of the ViewPager, since there are multiple photos/ captions sharing the same layout, it only returned the 1st TextView ID, thus the hide/ show function only works on the 1st photo caption but not the rest.

Question: How do I make it work for all TextView's?

Thanks!


Solution

  • I did it! Here's how:

    1. Within each ViewPager there is a fragment, often contains an ImageView which is its main View component.
    2. Since I've already been tracking the ImageView OnClickListener in each fragment and passed back to the Activity, I have an OnClick(View v) method in the Activity.
    3. In the OnClick(View v), I get the parent View of the current ImageView using (View) getParent() to get the ViewPager parent container (of the current page).
    4. Once you get the parent View, you can find its child TextView id using (TextView) parent.findViewById()

    Bonus: the code:

        public void onClick(View v) {
                // since each pager includes an ImageView and a TextView
                // get the current pager which is the parent of the current ImageView
                View currentPage = (View) v.getParent();
                // find the TextView within the current page
                mCaption = (TextView) currentPage.findViewById(R.id.caption);
        ...
    

    Done!