Skip to content

Instantly share code, notes, and snippets.

@catvec
Created August 24, 2014 16:35
Show Gist options
  • Save catvec/50530e98a47490e6abea to your computer and use it in GitHub Desktop.
Save catvec/50530e98a47490e6abea to your computer and use it in GitHub Desktop.
How I use fragments
/* My Fragment Class */
public class MainFragment extends Fragment {
private View mainView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
mainView = inflater.inflate(R.layout.fragment_main, container, false);
mainView.setVisibility(View.GONE);
return mainView;
}
}
/* XML Layout */
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/mainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="fragments.MainFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/signed_in_message"/>
</RelativeLayout>
/* Switching out fragments */
public class FragmentHelper {
private Intent intent;
private FragmentManager fragmentManager;
public FragmentHelper(Intent intent, FragmentManager fragmentManager){
this.intent = intent;
this.fragmentManager = fragmentManager;
}
public void switchFragment(Fragment fragment, int frameLayout){
fragment.setArguments(this.intent.getExtras());
this.fragmentManager.beginTransaction().replace(frameLayout, fragment).addToBackStack(null).commit();
}
}
FragmentHelper fragmentHelper = new FragmentHelper(getIntent(), getSupportFragmentManager());
fragmentHelper.switchFragment(new SignInFragment(), R.id.mainFragment);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment