How to go other Tabs by clicking on a Button from the current Tab in Android?

后端 未结 3 1124
生来不讨喜
生来不讨喜 2021-02-15 17:40

I trying to write a code in Android, to switch from one tab to another tab by click on a button.

I know to by clicking on tab we can switch from one tab to another but c

相关标签:
3条回答
  • 2021-02-15 18:11

    your ViewPager is null because you are not initializing the variable.

    You need do

    public class MoviesFragment extends Fragment {
    
    ViewPager viewPager;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle    savedInstanceState) 
    {
    
       View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
    
       Button btn = (Button) rootView.findViewById(R.id.btn);
       viewPager = (ViewPager) rootView.findViewById(R.id.some_viewpager);//Initializing
       btn.setOnClickListener(new View.OnClickListener() 
       {
    
           @Override
          public void onClick(View v) 
          {
    
              viewPager.setCurrentItem(0);
    
          }
      }); 
    
    
     return rootView;
    }}
    
    0 讨论(0)
  • 2021-02-15 18:16
       viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
         viewPager.setCurrentItem(0);
    

    inside your fragment

    0 讨论(0)
  • 2021-02-15 18:24

    You have to call parent view inside your fragment.

    public class MoviesFragment extends Fragment {
    
         ViewPager viewPager;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
    
            Button btn = (Button) rootView.findViewById(R.id.btn);
            viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
    
               btn.setOnClickListener(new View.OnClickListener() 
               {
    
                   @Override
                  public void onClick(View v) 
                  {
                       viewPager.setCurrentItem(0);
    
    
                  }
              }); 
    
            return rootView;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题