So I have two fragments, say Fragment1 and Fragment2 . And both has its own layout file. On first fragment (Fragment1) there are six buttons. So when I click on first button, I want it to display the Fragment2 But both are overlapping when I Click on the first Button.
Check Screenshot Below
THIS IS THE FRAGMENT1
THIS IS THE FRAGMENT2 AND It's Overlapping WITH FRAGMENT1
I Used Every Possible Solutions But None Works. i set background to white or black even images. none works.
My code on mainActivity
public void button1click (View view) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frag1,new Fragment2());
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
Fragment1
public class Fragment1 extends Fragment {
public class onClicks extends AppCompatActivity {
}
View myView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment1_layout, container, false);
return myView;
}}
Fragment2
public class Fragment2 extends Fragment {
public Fragment2 () {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment2_layout, container, false);
}}
fragment1_layout. This is fragment1_layout
fragment2_layout. THIS is the fragment2_layout
Please check what's wrong.
The docs suggest you always use FrameLayout to replace fragments. I see this problem in your code in this line
fragmentTransaction.replace(R.id.frag1,new Fragment2());
It seems you don't have a container (FrameLayout) to replace your fragments in it. To fix this possible design issue , you should create an xml for your Main Activity there add a FrameLayout with id "container" for example. Then, use it in code this way
public void button1click (View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container,new Fragment2());
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
Then you should in onCreate() method of your activity add fragment1 to your container so that you don't get blank screen when opening the app