Android ViewPager get the current View

前端 未结 15 2346
天命终不由人
天命终不由人 2020-11-28 06:24

I have a ViewPager, and I\'d like to get the current selected and visible view, not a position.

  1. getChildAt(getCurrentItem) returns wrong Vi
15条回答
  •  迷失自我
    2020-11-28 06:29

    If you do not have many pages and you can safely apply setOffscreenPageLimit(N-1) where N is the total number of pages without wasting too much memory then you could do the following:

    public Object instantiateItem(final ViewGroup container, final int position) {      
        CustomHomeView RL = new CustomHomeView(context);
        if (position==0){
            container.setId(R.id.home_container);} ...rest of code
    

    then here is code to access your page

    ((ViewGroup)pager.findViewById(R.id.home_container)).getChildAt(pager.getCurrentItem()).setBackgroundColor(Color.BLUE);
    

    If you want you can set up a method for accessing a page

    RelativeLayout getPageAt(int index){
        RelativeLayout rl =  ((RelativeLayout)((ViewGroup)pager.findViewById(R.id.home_container)).getChildAt(index));
        return rl;
    }
    

提交回复
热议问题