I'm trying to implement a base activity with DrawerLayout so I can extend it to other activities.
I used the default Drawer Application in the Eclipse wizard and the help of these questions: Q1, Q2, and for some reason I get an inflate exception when I launch the app.
public class BaseActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private FrameLayout mFrameLayout;
#Override
public void setContentView(int layoutResID) {
mDrawerLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.activity_base, null);
mFrameLayout = (FrameLayout) mDrawerLayout.findViewById(R.id.container);
getLayoutInflater().inflate(layoutResID, mFrameLayout, true); /* Exception Here */
super.setContentView(mDrawerLayout);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, mDrawerLayout);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
case 0:
fragmentManager.beginTransaction()
.replace(R.id.container, new AllCategoriesFragment()).commit();
break;
case 1:
fragmentManager.beginTransaction()
.replace(R.id.container, new AllRecipesFragment()).commit();
break;
}
}
activity_base.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.yonivy.cookpad.app.BaseActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/navigation_drawer"
android:name="com.yonivy.cookpad.app.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
AllCategoriesFragment.java
public class AllCategoriesFragment extends Fragment {
private ArrayList<Category> allCategories;
private CategoriesAdapter cAdapter;
private ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_all_categories, container, false);
lv = (ListView) view.findViewById(R.id.mList);
displayAllCategories();
return view;
}
Sample extended class
public class RecipeActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
// ...
}
Related
After searching for some time, I still didn't find the solution to my problem and since I'm a beginner, I don't really know what to do. I want to change the layout/fragment file when I click on another tab but it should still be connected to my MainActivity. The code is the Android Studio example code.
First Tab:
Second Tab:
So basically it should change the fragment when I change the tab. Unfortunately I don't know how to implement this in my code.
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
//FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//fab.setOnClickListener(new View.OnClickListener() {
//public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//.setAction("Action", null).show();
//}
//});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(this, "Derzeit keine Einstellungen vorhanden.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
Looking forward for your answers. I'm getting desperate.
You need to create the layout for this, with a TabLayout and a ViewPager:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
In your MainActivity.java, you need to initialize the views and add the fragments using an Adapter:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Frag1(), "FRAG 1");
adapter.addFragment(new Frag2(), "FRAG 2");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
Adapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Now you only need to add the Fragments to the adpater and define them.
For fragments, you can override the onCreate method and inflate the layouts.
public class Frag2 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_frag2, container, false);
return view;
}
}
The activity defined earlier is just enough to handle the fragments. There may be more better ways than this, but this is simple enough.
I have a MainActivIty and it supports two fragments i.e Home and Profile.Home has a TabLayout which in turn has three fragments Trending,Followed and Nearby.
So the issue is when Home is first time loaded it shows the content of the Tab fragments and slider of tab layout moves properly but when I got to profile and then to home then the tab layout fragments do not load and while swiping left to right slider does not move smoothly.Here is the code.
public class MainActivity extends AppCompatActivity {
ImageButton home_btn,myProfile_btn;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
TextView txt_action_bar;
Home home;
ProfileFragment profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
home_btn=(ImageButton)findViewById(R.id.home_btn) ;
discover_btn=(ImageButton)findViewById(R.id.discover_btn) ;
myProfile_btn=(ImageButton)findViewById(R.id.profile_btn) ;
notification_btn=(ImageButton)findViewById(R.id.notification_btn) ;
plus_btn=(ImageButton)findViewById(R.id.btn_plus) ;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
txt_action_bar = (TextView)findViewById(R.id.toolbar_title);
displayMetrics = getResources().getDisplayMetrics();
Typeface custom_font = Typeface.createFromAsset(getAssets(),"fonts/NoteworthyLight.ttf");
txt_action_bar.setTypeface(custom_font);
setSupportActionBar(toolbar);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
home = new Home();
profile = new ProfileFragment();
fragmentTransaction.add(R.id.main_fragment_container,home,"home");
fragmentTransaction.commit();
}
public void onClickHome(View view)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment_container,home,"home");
fragmentTransaction.commit();
}
public void onClickMyProfile(View view)
{
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment_container,profile,"profile");
fragmentTransaction.commit();
}
}
Home.java
public class Home extends Fragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public Home() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_home, container, false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) view.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
return view;
}
FollowedFragment.java
public class FollowedFragment extends Fragment {
public FollowedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.feeds_list, container, false);
new DownloadFollowedFeeds().execute();
return rootView;
}
fragment_home.xml
<LinearLayout android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
style="#style/TabNameStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/medium_turquoise"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="fill_parent"/>
SectionPagerAdapter.java
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = new String[] { "Trending", "Followed","Nearby" };
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
Log.i("tag","number"+String.valueOf(position));
if(position==0) return new TrendingFragment();
else if(position==1) return new FollowedFragment();
else return new NearbyFragment();
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
As answered here:
When you are creating the view adapter in Home.java:
instead of
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
you should do,
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
Hi I'm new to programming and android studio, I am having trouble adding a ListView in my Java Class Fragment after I already set the class up for a Navigation Drawer Fragment. I have successfully created an app that navigates through the different fragments but once a fragment is selected the ListView I set up in the xml layout does not appear. What I would like my app to do is have a navigation drawer that takes you to different workout types (i.e. gym workouts, calisthenics workouts) then once you select the type of workout for the Navigation Drawer it will open a ListView of all the workouts available to that type. I don't know how to implement a List view in a Navigation Drawer Fragment. My code is provided below. Some of my code is below.
If anyone would help me with this it will be much appreciated!
-----activity_main.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" android:background="#fffdfd">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/home_page"/>
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.teamdnafitness.myapp.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
--One of my fragments.xml---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/calList"></ListView>
</LinearLayout>
---MY MainActivity.java---
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, gymWorkoutsFragment.newInstance())
.commit();
} else if(position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, calisthenicsWorkoutsFragment.newInstance())
.commit();
} else if(position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, motivationalVideosFragment.newInstance())
.commit();
}
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
--My Calisthenics Java Class--
public class calisthenicsWorkoutsFragment extends Fragment{
public static calisthenicsWorkoutsFragment newInstance(){
calisthenicsWorkoutsFragment fragment = new calisthenicsWorkoutsFragment();
return fragment;
}
public calisthenicsWorkoutsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calisthenics_workouts, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
I have a activity which contains of navigation drawer, in that class my navigation items point to fragment classes, In one of the fragment classes i am using a dynamic view pager to display items, but how can i use fragment manager of fragment class as a argument of view pager which needs fragment argument of fragment activity or activity, Need some solutions.
I'm doing something similar right now. I only have the the ViewPager below the navigation drawer, but if you have a more complicated layout the same principal should work.
To start, I have the activity layout (most of this was generated by Android Studio)
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.you.yourapp.YourActivity">
<FrameLayout android:id="#+id/your_container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.you.yourapp.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
The activity uses the FragmentManager to swap in another fragment that contains the ViewPager into the FrameLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your);
...
Fragment fragment = YourFragment.newInstance(Bundle args);
getSupportFragmentManager()
.beginTransaction().replace(R.id.your_container, fragment)
.commit();
}
The Fragment that has the ViewPager is simple
<android.support.v4.view.ViewPager android:id="#+id/your_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
in YourFragment.java implement your FragmentPagerAdapter(you could do this as an inner class, but I ran into problems with static allocation, plus this is cleaner)
public class YourFragment extends android.support.v4.app.Fragment {
private ViewPager mPager;
public YourFragment() {
}
public static TaskFragment newInstance(Uri uri, String outlineText) {
TaskFragment fragment = new YourFragment();
Bundle args = new Bundle();
//set args
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_your, null);
mPager = (ViewPager) rootView.findViewById(R.id.your_view_pager);
TaskPagerAdapter adapter = new TaskPagerAdapter(getFragmentManager());
mPager.setAdapter(adapter);
return rootView;
}
...
private class YourPagerAdapter extends FragmentStatePagerAdapter {
public YourPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return count; //however you get the count
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
//set the arguments for your page
return PageFragment.newInstance(args);
}
}
}
ETA:
So now implement a custom interface for your navigation drawer callbacks
...
private NavigationDrawerCallbacks mCallbacks
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (NavigationDrawerCallbacks) activity;
}
...
#Override
public void onClick(View view) { //whatever your click listener is
Fragment fragment = getFragmentSomehow(); //get your fragment
mCallbacks.onNavigationItemSelected(fragment);
}
...
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(Fragment fragment);
}
Now have YourActivity implement this interface
public class YourFragment extends Activity
implements NavigationDrawerCallbacks
{
...
#Override
public void onNavigationDrawerItemSelected(Fragment fragment) {
getSupportFragmentManeger()
.beginTransaction()
.replace(R.id.you_container, fragment)
.commit();
}
...
}
I think this is what you mean to do.
Hope this helps
I am trying to change the layout, or inflate the layout, of the main activity to the About activity when one of the items is clicked in the navigation drawer.
This is how my main activity looks
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment holderFragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
switch (sectionNumber) {
case 1:
bundle.putInt(ARG_SECTION_NUMBER, 05);
break;
case 2:
fragment = new About();
bundle.putInt(ARG_SECTION_NUMBER, 16);
break;
case 3:
bundle.putInt(ARG_SECTION_NUMBER, 1991);
break;
}
holderFragment.setArguments(bundle);
return holderFragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
my main activity .xml looks like this
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="com.projectname.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
I have a fragment_about.xml
and this is how the about class looks.
public class About extends Fragment {
public About(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about, container, false);
return rootView;
}
}
this is how my fragment_main.xml looks like
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.projectname.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
the navigation drawer works fine but it only changes a text view, i cant figure out how to change the entire layout from the main activity to the about activity on the click of an item in the drawer.
i Just don't know what to do, every time i do something i get an error.
First of all you should extend the FragmentActivity class by your MainActivity. Then in NavigationDrawer click listener do this:
RelativeLayout l = (RelativeLayout) findViewById(R.id.container);
FragmentManager manager = getSupportFragmentManager();
About fragment = new About();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
And remove from fragment_main (if you not gonna use next like one deeper fragment).