I'm trying to switch a fragment when a button is pressed inside fragment itself and if an error is thrown by new fragment it will change back to the first fragment. I followed other answer, but none worked, what I get is always a blank fragment.
My main activity is a AppCompatActivity
. This is a part of onCreate()
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
viewPager = (ViewPager) findViewById(R.id.viewpager);
FragmentAdapter pageAdapter = new FragmentAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pageAdapter);
}
In main acivity I've this function to switch fragment
public void switchFragment(){
Fragment fragment = null;
try {
fragment = SecondFragment.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.viewpager, fragment).commit();
}
And inside FirstFragment class:
((MainActivity) activityReference.get().getActivity()).switchFragment();
On startup the first fragmet is active and works well, when I press the button that call switchFragment()
it become white. What did I miss?