Should I use a nested fragment for tabs in a fragment? - android

I have a Main Activity which uses an AHBottomNavigationView for a menu at the bottom of the screen. When a different menu item is clicked, it creates a new fragment corresponding to that menu item with logic like so (condensed switch statement for the simplicity of this question):
fragmentManager.beginTransaction().replace(R.id.content_id, New TheFragmentForTheTabClicked).commit();
Where content_id is the ID of the Main Activity's ConstraintLayout.
Within the fragment for my first navigation menu item, there are two more tabs (using TabLayout), which replace the screen space with another fragment. This is done with a FragmentPagerAdapter, which is set onto a ViewPager, so tapping each tab changes the sub fragment. So at this point, there is a fragment nested in a fragment nested in a class. Here is what it generally is:
Main Activity
|
+-- Fragment 1 (selected from AHBottomNavigationView)
| |
| +-- Sub-Fragment 1 (selected by clicking the first tab in Fragment 1)
| |
| +-- Sub-Fragment 2 (selected by clicking the second tab in Fragment 1)
|
+-- Fragment 2 (selected from AHBottomNavigationView)
|
+-- Fragment 3 (selected from AHBottomNavigationView)
|
+-- Fragment 4 (selected from AHBottomNavigationView)
So my question is this:
Is the way I am doing this correct, and if not, what would a better way be?
Also, I'm finding that When I tab to Fragment 1 the first time, the swiping and tapping between the two tabs works fine, however if I tap a different bottom navigation menu item (i.e. Fragment 3) and then go back, I get the following 2 issues:
The content in either of the subfragments is not shown
Swiping between the two tabs no longer works. Instead of one motion moving to the different tab, I have to pull across the screen entirely because the indicator gets "stuck" part way between two tabs.
If there is any more information that I can provide, please let me know and I will.
Fragment1.java:
package com.mypackage.mypackage;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class Fragment1 extends Fragment {
private FragmentActivity mContext;
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) getView().findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
// using getFragmentManager() will work too
Fragment1PagerAdapter adapter = new Fragment1PagerAdapter(mContext.getSupportFragmentManager(), mContext);
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
/**
* Override to set context. This context is used for getSupportFragmentManager in onCreateView
* #param activity
*/
#Override
public void onAttach(Activity activity) {
mContext=(FragmentActivity) activity;
super.onAttach(activity);
}
}
fragment_1.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabBackground="#color/fragment1TabBackground"
app:tabIndicatorColor="#color/fragment1TabIndicatorColor"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Fragment1PagerAdapter.java
package com.mypackage.mypackage;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.Context;
public class Fragment1PagerAdapter extends FragmentPagerAdapter {
private Context context;
public Fragment1PagerAdapter(FragmentManager fm, Context mContext){
super(fm);
context = mContext;
}
#Override
public Fragment getItem(int position){
if (position == 0){
return new SubFragment1();
}
else{
return new SubFragment2();
}
}
#Override
public int getCount() {return 2;}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getResources().getString(R.string.sub_fragment_1_page_title);
case 1:
return context.getResources().getString(R.string.sub_fragment_2_page_title);
default:
return null;
}
}
}

When nesting Fragments inside Fragment with ViewPager and swipe feature as FragmentManager which needs to be provided to Adapter recommended is to use: getChildFragmentManager() instead of getSupportFragmentManager() or getFragmentManager(). Because both are actually related to Activities instead of getChildFragmentManager(), as documentation says, is related to Fragment:
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.

Related

ViewPager2 preloaing next fragment even when offsetlimit is the default(0)

I am facing this rather strange problem with viewPager2.
I did some reading and found out that viewPager2 has a default offset limit of 0 which is perfect for my application.
I'm using it with a tab layout and I have 3 fragments (Home, Profile, Notification).
When the activity loads and the first fragment(Home) loads, I can see in my logcat that the next fragment(Profile) is not loaded, as expected.
But when I click on the profile tab something strange happens, the next tab(Notification) is preloaded. The methods
onAttach,onCreate,onCreateView,onActivityCreated,onStart for the Notification tab is called.
Why is this doing so and how to I fix this ?
Logcat Screenshot
I have attached a screen shot of my logcat here.
Thankyou in advance.
I Assume you mean OFFSCREEN_PAGE_LIMIT_DEFAULT not offsetlimit as you are talking about a preloading of fragments problem.
And the default value is -1 not zero https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2.html#OFFSCREEN_PAGE_LIMIT_DEFAULT
and the default means
Value to indicate that the default caching mechanism of RecyclerView should be used instead of explicitly prefetch and retain pages to either side of the current page.
As this is a performance optimisation of the recyclerview, I would say it's not a guarantee that it won't preload your fragments, it's just left to the caching mechanism of the recyclerview to decide.
There are a number of factors that can affect the recyclerview's caching mechanism.
If preloading of your fragment is a problem because you have dynamic data in it that you only want to be loaded when the page is shown then it would be better to move your fragment to use a "lazy loading" method i.e. only load the data when it is shown.
I had a similar problem with the original viewpager and solved it with "lazy loading". If the timing of loading of your dynamic data is the problem then update the question and then I can outline a possible solution.
Update:3
It seems that Viewpager2 actually works correctly with the Fragments lifecycle unlike the original Viewpager thus you can call updateView() as shown in update2 example from the Fragments onResume method without having to use the pageSelected callback via the Adapter to trigger the update of the View.
Update:
I believe the actual cause from looking at the viewpager2 code is that selecting the Tab does a fake drag with smooth scrolling and smooth scrolling adds the selected item +1 to the cache, if you swipe from Tab0 to Tab1 yourself it does not create Tab2
ViewPager2 is a bit different and "lazy loading" method I used for the original ViewPager does not totally fit but there is a slightly different way to do the same.
The main idea with the original ViewPager was to update the view ONLY when a page was selected using a onPageChangeListener but ViewPager2 uses a callback instead
So add the following after you have created the ViewPager2 (in the Activity onCreate usually)
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// Tell the recyclerview that position 2 has changed when selected
// Thus it recreates it updating the dynamic data
if (position == 2) {
// the adapter for the ViewPager needs to a member of the Activity class so accessible here
adapter.notifyItemChanged(position);
}
}
});
This is simpler but has a minor drawback that the dynamic data is loaded when it is preloaded and then again when it is actually displayed.
Update2:
A more efficient addition to first method more similar to my original approach
This is a full working example as it is easier to explain.
The main idea is in your fragment with the dynamic data that you ONLY want to load when it is displayed is to create an empty "placeholder" view item and you don't fill it with data in the Fragments onViewCreated, in this example it is a second textview with no text but could be a recyclerview with zero objects or any other type of view.
In your Fragment you then create a method to update the "placeholder" with the data (in this case the method is called updateView() which sets the textview text to the current date and time)
Then in your Fragment Adapter you store a reference to each fragment it creates in a ArrayList (this allows you get the fragment back) and you then create an updateFragment() method in the adapter that uses the position to get the Fragment to be able to call the updateView() on it.
Finally again you use onPageSelected to call the updateFragment with the position you want to dynamically update.
So textview1 shows the data and time the fragement was created and textview2 is only shown on the third Tab and has a date and time on when page was selected. Note that texview1 on "Tab 2" and "Tab 3" is the same time when you click on the "Tab 2" headers to change tabs (this is the problem in the question)
MainActivity.java
package com.test.viewpager2;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager2;
ViewPager2Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewpager2);
tabLayout = findViewById(R.id.tabLayout);
viewPager2.setAdapter(createCardAdapter());
new TabLayoutMediator(tabLayout, viewPager2,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// Tell the recyclerview that position 2 has changed when selected
// Thus it recreates it updating the dynamic data
if (position == 2) {
adapter.updateFragment(position);
}
}
});
}
private ViewPager2Adapter createCardAdapter() {
adapter = new ViewPager2Adapter(this);
return adapter;
}
}
ViewPager2Adapter.java
package com.test.viewpager2;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
public class ViewPager2Adapter extends FragmentStateAdapter {
private static final int numOfTabs = 3;
private ArrayList<Fragment> fragments = new ArrayList<>();
public ViewPager2Adapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull #Override public Fragment createFragment(int position){
Fragment fragment = TextFragment.newInstance(position);
fragments.add(fragment);
return fragment;
}
#Override
public int getItemCount(){
return numOfTabs;
}
public void updateFragment(int position){
Fragment fragment = fragments.get(position);
// Check fragment type to make sure it is one we know has an updateView Method
if (fragment instanceof TextFragment){
TextFragment textFragment = (TextFragment) fragment;
textFragment.updateView();
}
}
}
TextFragment.java
package com.test.viewpager2;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class TextFragment extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private int mParam1;
private View view;
public TextFragment() {
// Required empty public constructor
}
public static TextFragment newInstance(int param1) {
TextFragment fragment = new TextFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d("Frag", "newInstance");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
Log.d("Frag", "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d("Frag", "onCreateView");
view = inflater.inflate(R.layout.fragment_text, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
TextView textView1 = view.findViewById(R.id.textview1);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss.sss", Locale.US);
String dt = df.format(Calendar.getInstance().getTime());
textView1.setText(dt);
}
public void updateView(){
Log.d("Frag", "updateView");
TextView textView2 = view.findViewById(R.id.textview2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss.sss", Locale.US);
String dt = df.format(Calendar.getInstance().getTime());
textView2.setText(dt);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d("Frag", "onAttach");
}
#Override
public void onDetach() {
super.onDetach();
Log.d("Frag", "onDetach");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewpager2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tabLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextFragment">
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/textview1" />/>
</androidx.constraintlayout.widget.ConstraintLayout>
You need to notify adapter on every scroll.
pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) {
myToast(applicationContext, "1 changes $position")
tapPosition = position
super.onPageSelected(position)
}
override fun onPageScrollStateChanged(state: Int) {
if (state.equals(0))
{
pagerAdapter.notifyItemChanged(tapPosition)
}
super.onPageScrollStateChanged(state)
}
})
onPageScrollStateChanged here you must notify adapter.

Blank fragment after navigation with BottomNav and TabMenu

I am developing an Android app that has a little bit confusing navigation structure which leads me to my problem. There are two ways to navigate through the app. First is the BottomNav and second is a TabMenu. I thought about working with fragments that replace each other, so I came up with the following structure:
1. BottomNav#1
- TabMenu#1
- Tabmenu#2
- TabMenu#3
- ...
2. BottomNav#2
- TabMenu#4
- Tabmenu#5
- TabMenu#6
- ...
... and so on.
The problem I am facing is that when I navigate from BottomNav#1 to BottomNav#2 and back again there is a blank screen that doesn't show the content of the actual fragment:
When I open the app
After clicking on BottomNav#2 and then back to BottomNav#1 the fragment seems to be blank
My guess is that I somehow have a problem with my fragmentTransaction.replace(); as it seems like the fragment doesn't get loaded again? I am kind of new to this and really tried to find an answer online but this is a bit specific why I guess I didn't find anything.
This is my MainActivity:
package com.example.XXXX;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private FrameLayout mMainFrame;
private AusweisFragment ausweisFragment;
private SpendenFragment spendenFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ausweisFragment = new AusweisFragment();
spendenFragment = new SpendenFragment();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{
switch (item.getItemId())
{
case R.id.navigation_ausweis:
setFragment(ausweisFragment);
return true;
case R.id.navigation_spenden:
setFragment(spendenFragment);
return true;
}
return false;
}
};
private void setFragment(Fragment fragment)
{
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
This should lead to e.g. the fragment called "ausweis" by clicking on on BottomNav#1 (switch case):
package com.example.XXXXXXX;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TabItem;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AusweisFragment extends Fragment {
private View rootView;
private AusweisPageAdapter ausweisPageAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
public AusweisFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
rootView= inflater.inflate(R.layout.fragment_ausweis, container, false);
tabLayout = rootView.findViewById(R.id.tablayoutAusweis);
viewPager = rootView.findViewById(R.id.viewPagerAusweis);
ausweisPageAdapter = new AusweisPageAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(ausweisPageAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootView;
}
}
After that I would like to call another fragment called "spenden" which is exactly the same as the fragment called "ausweis" but with different named tabs, so I think it is not bother you with more code.
edit: I missed about writing where the "content" I wrote about gets from. For a first try and proof that the fragments change, I hardcoded a phrase like "Ausweis" into the XML which is connected to my fragment java class.
Maybe one of you has an idea to that problem. I think it has something to do with my onCreateView in one of the fragments, but I have no close clue.
Hopefuly I didn't miss an important detail. I am very grateful for any kind of help. Thanks a lot in advance.
The answer to my problem was to use a child-parent relation between the different fragments. With the click on BottomNav#1 I am inflating an fragment which inflates a new fragment inside itself. That was the key problem. In my code I handled this as a second "normal" getFragmentManager();.
The answer is to use getChildFragmentManager(); for the nested fragment instead. Like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
rootView= inflater.inflate(R.layout.fragment_ausweis, container, false);
tabLayout1 = rootView.findViewById(R.id.tablayoutAusweis);
viewPager = rootView.findViewById(R.id.viewPagerAusweis);
ausweisPageAdapter = new AusweisPageAdapter(getChildFragmentManager(), tabLayout1.getTabCount());
viewPager.setAdapter(ausweisPageAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
...
...
Hopefuly this will help some people when they face the same problem with nested fragments.

onclick event in fragment activity not working

I have a activity A in which I have a fragment.
In this activity Fragment changes to fragment A(default when activity A is called) or fragment B based on user input in activity A.
In both fragments A & B I have a button with on click listener. but this button works only for the first time when activity A is started.
when user changes fragment the button in those fragments stop responding to on click.
Please suggest what I need to do in order to make buttons in fragment A & B work when fragments are changed by user.
I am replacing fragments based on user input by this code:
fr = new FragmentOneDice();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
In fragment activity code is like this for on click listener button.
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.Collections;
public class FragmentOneDice extends Fragment implements View.OnClickListener {
Button button1;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_fragment_one, container, false);
button1 = (Button) view.findViewById(R.id.button_one);
button1.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
//MY CODE HERE
}
The problem was in my activity_main.XML, where I had defined <Fragment> as a placeholder for all fragments and had set one fragment as default. So when other fragment was loaded it was getting overlapped resulting in on click event on the button not working, I changed the <Fragment> to <FrameLayout> as a placeholder. And my problem was solved.
First You remember one thing,
fragment to fragment direct transaction,or fragment to fragment direct replacement is not possible. it is possible only throw the Activity.
Define a interface in your first fragment and make container Activity to implement that interface, so you can send your data from Fragment to Activity .In another hand create Second Fragment and define a interface in it. In Content Activity inside implemented methods of First Fragment interface on that define a Second Fragment ,here we assign a data to the second Fragment through interface.

Android FragmentActivity from inside Fragment

In my Android application I have created a simple Navigation Drawer which calls fragments when an item is clicked. From one of these fragments, I want to call a FragmentActivity (which will make scrollable tabs from within one of my fragments). Is this possible? Can someone please help me. A similar example to what I'm trying to achieve is in Play Music. It has a Navigation Drawer and upon selecting 'My Library' it creates a Fragment with scrollable tabs whilst still having the NavDrawer accessible from that page.
Regards,
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import cgg.gov.in.apps.eoffice.source.R;
public class TestTabsinsideFragment extends Fragment
{
View rootView;
public TestTabsinsideFragment ()
{
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Apply the layout for the fragment
rootView = inflater.inflate(R.layout.approve_leaves, container, false);
getActivity().setTitle("New tabbed layout inside Fragment :-) ");
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i1 = 0; i1 < 3; i1++) {
getActivity().getActionBar().addTab(
getActivity().getActionBar().newTab()
.setText("Tab " + (i1 + 1))
.setTabListener(tabListener));
}
return rootView;
}
Did this answer your question ??
Include this code in your Fragment and call it from onSelectItem() of Nav-Drawer

method getfragmentmanager() is undefined

I am making a view pager to make a slide show for images. I took code from Android developers, but I was facing some issues, fragment was not recognized, I think it was because my android was 2.33. So to solve that I imported a jar file android.support.v4.jar
My issues were resolved but now I am getting this error that getfragmentmanager() is undefined
and another issue "The method invalidateOptionsMenu() is undefined for the type new ViewPager.SimpleOnPageChangeListener(){}"
Here is my code, can any one please help ??
My platform is 2.3.3 and api level is 10 and in manifest I have this
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
Code :
package com.example.profilemanagment;
import android.support.v4.app.Fragment;
import android.support.v4.app.*;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When changing pages, reset the action bar actions since they are dependent
// on which page is currently active. An alternative approach is to have each
// fragment expose actions itself (rather than the activity exposing actions),
// but for simplicity, the activity provides the actions in this sample.
invalidateOptionsMenu();
}
});
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
Quoting from the docs.
When using this class (FragmentActivity) as opposed to new platform's built-in fragment and loader support, you must use the getSupportFragmentManager() and getSupportLoaderManager() methods respectively to access those features.
Since you are extending FragmentActivity use getSupportFragmentManager()
http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html
Check the docs
FragmentActivity does not have getFragmentManager()

Categories

Resources