Search code examples
javaandroidandroid-layoutandroid-fragmentsandroid-viewpager

I want to make a button visible when ViewPager get's to page 4, but I get null pointer exception


one thing that I found accidentally is that when I put the code in a postDelayed handler it works fine. how can I make it work without postDelayed handler?

public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        final SlideFragment fragment = new SlideFragment();
        if (position == 3){

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragment.btnStart.setVisibility(View.VISIBLE);
                }
            },0);
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

}

Solution

  • The problem is that your views might not be getting creating on time for you to call the setVisibility on them. Ideally you'd pass an argument when you create the fragment and from them act on the fragment.

    if (position == 3){
        final SlideFragment fragment = new SlideFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("BUTTON_VISIBILITY", true);
        fragment.setArguments(bundle);
    }
    

    Then in your fragment:

    public View onCreateView(LayoutInflater inflater,
             ViewGroup containerObject,
             Bundle savedInstanceState){
             //here is your arguments
             Bundle bundle= getArguments(); 
    
            View view =  inflater.inflate(R.layout.your_fragment_layout, container, false);
            btnStart = view.findViewById(R.id.id_of_your_button);
            if(bundle!=null){
               if(bundle.getBoolean("BUTTON_VISIBILITY", false)){
                  btnStart.setVisibility(View.VISIBLE);
               } 
            }
         return view;
         }
    

    EDIT

    You can use onViewCreated to make sure everythin has been created:

       public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState){
                    return  inflater.inflate(R.layout.your_fragment_layout, container, false); 
                 }
    
       public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            Bundle bundle= getArguments(); 
            btnStart = view.findViewById(R.id.id_of_your_button);
                if(bundle!=null){
                   if(bundle.getBoolean("BUTTON_VISIBILITY", false)){
                      btnStart.setVisibility(View.VISIBLE);
                   } 
                }
        }