I have tried every tutorial on the first google page about android fragments, but I can\'t get anything to work.
So I have one navigation bar activity, MainAct
This is FrameLayout
<FrameLayout
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/view"
android:layout_marginTop="@dimen/medium_margin"></FrameLayout>
Now , call displayview method onCreate() of your activity,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//rest of your code here
displayView(0); // fragment at 0 position
}
displayView method, which have three fragements
public void displayView(int position) {
switch (position) {
case 0:
tvTitle.setText(getResources().getString(R.string.signin_tile));
showFragment(new LoginFragment(), position);
break;
case 1:
tvTitle.setText(getResources().getString(R.string.forgot_password_tile));
showFragment(new ForgotPasswordFragment(), position);
break;
case 2:
tvTitle.setText(getResources().getString(R.string.change_password_tile));
showFragment(new ChangePasswordFragment(), position);
break;
}
}
showFragment method called from displayView method,
public void showFragment(Fragment fragment, int position) {
FragmentTransaction mTransactiont = getSupportFragmentManager().beginTransaction();
mTransactiont.replace(R.id.main_container, fragment, fragment.getClass().getName());
mTransactiont.commit();
}
I solved it!
Apparently, I had to use android.support.v4.app.Fragment;
instead of android.app.Fragment;
.
This is the code I got it to work with:
protected void setFragment(Fragment fragment) {
android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.fragment_container, fragment);
t.commit();
}
And to set it (from the nav bar onNavigationItemSelected()
, you do this:
setFragment(new RoosterFragment());
I hope this helps others out with the same frustrating problem.
Try this one. it is my newbie code easier to understand :)
FragmentTransaction transaction;
switch (id){
case R.id.button_fragment_one:
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, new FragmentOne());
transaction.addToBackStack(null);
transaction.commit();
break;
case R.id.button_fragment_two:
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, new FragmentTwo());
transaction.commit();
break;
default:
break;
}
Did you try this? Click here
This link will Help you, to create fragment
.
and this is what you want for navigation drawerClick here