How to attach existing fragment - android

How can I attach existing fragment, when change back tab in ActionBar.NAVIGATION_MODE_TABS?
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.detach(fragment);
}
}

You can verify if your fragment was loaded previously in the fragment stack. Also could store all your used fragments to reuse it
public void setFragment(Fragment fragmentInstance) {
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
Fragment oldFragmentInstance = fragmentManager
.findFragmentById(R.id.curr_fragment);
boolean onlyAttach = false;
List<Fragment> prevFragments = getSupportFragmentManager()
.getFragments();
for (Fragment fragment : prevFragments) {
if (fragment == null) {
continue;
}
if (fragment.getClass().equals(fragmentInstance.getClass())) {
onlyAttach = true;
fragmentInstance = fragment;
break;
}
}
fragmentTransaction.detach(oldFragmentInstance);
if (onlyAttach) {
fragmentTransaction.attach(fragmentInstance);
} else {
fragmentTransaction.replace(R.id.curr_fragment,
fragmentInstance);
fragmentTransaction.addToBackStack(null);
}
try {
fragmentTransaction.commit();
}
}
Hope this helps

Related

Using unknown number of tabs

I want to create an activity that can display any number of tabs, without creating an activity for each tab.
Is it possible?
The only way I saw creating tabs included creating an activity for each one.
You can try as follows ,
Extend your activity from ActionBarActivity and add required number of tabs programmatically ,
ActionBar.TabListener tabListener;
mactionBar = getActionBar();
mactionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabListener=new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
displayTabs(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
displayTabs(tab.getPosition());
}
};
mactionBar.addTab(mactionBar.newTab().setText(<any text>).setTabListener(tabListener));
//call the same method for required number of tabs
Call the same fragment for each tab click
private void displayTabs(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = new YourFragment();
break;
case 1:
fragment = new YourFragment();
break;
// same for required numder of cases
default:
break;
}
if (fragment != null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(<container id>, fragment).commit();
}
}

NullPointerException : FragmentManager.beginTransaction()

I'm getting this error while trying to launch a Fragment from a first Fragment :
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
Here's the method where I'm getting the error :
#Override
public void onClick(View v) {
Fragment fragment = new PropertyFragment();
if (fragment != null) {
FragmentManager fragmentManager = fragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
fragmentTransaction.replace(R.id.rent_viewer, fragment);
fragmentTransaction.addToBackStack(null);
// Commit the transaction
fragmentTransaction.commit();
}
}
Precisely, the following code instruction is causing the error :
fragmentManager.beginTransaction();
Here's how the class and the nested class look like :
public class RentFragment extends Fragment {
...
#SuppressWarnings("unused")
private OnRentFragmentInteractionListener mListener;
public RentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnRentFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnRentFragmentInteractionListener");
}
}
#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_rent, container, false);
myOnClickListener = new RentOnClickListener(getActivity());
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnRentFragmentInteractionListener {
public void onRentFragmentInteraction(Uri uri);
}
private static class RentOnClickListener implements View.OnClickListener {
private final Context context;
private RentOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
Fragment fragment = new PropertyFragment();
if (fragment != null) {
FragmentManager fragmentManager = fragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
fragmentTransaction.replace(R.id.rent_viewer, fragment);
fragmentTransaction.addToBackStack(null);
// Commit the transaction
fragmentTransaction.commit();
}
}
}
}
FragmentManager will be null until it is attached to the activity.So use below code ,
If it is a nested Fragment use this.getChildFragmentManager() for your fragment class else use getActivity().getFragmentManager() or getActivity().getSupportFragmentManager().
Declare your FragmentTransaction and initialize it like this
FragmentTransaction fm;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
fm = getFragmentManager();
}
Then on your code, you can call this
Fragment fragment = new PropertyFragment();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.rent_viewer, fragment).addToBackStack(null).commit();;
Use the Customize Method in Base Class and use it.
public void replaceFragment(Fragment newFragment, Bundle bundle, boolean isAddToBackStack) {
String tag = newFragment.getClass().getSimpleName();
if (bundle != null) {
newFragment.setArguments(bundle);
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (getCurrentFragment() != null) {
ft.hide(getCurrentFragment());
}
ft.add(R.id.frameContainer, newFragment, tag);
newFragment.setRetainInstance(true);
if (isAddToBackStack) {
ft.addToBackStack(tag);
}
try {
ft.commitAllowingStateLoss();
} catch (Exception ex) {
ex.printStackTrace();
// ft.commitAllowingStateLoss();
}
}
You have to set context of activity as shown below on code HomeActivity.this.getSupportFragmentManager();
private Fragment fragment;
private FragmentManager fragmentManager;
fragmentManager=HomeActivity.this.getSupportFragmentManager();
transaction = fragmentManager.beginTransaction();
transaction.add(R.id.main_container, new ProfileFragment()).commit();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
fragmentTransaction.replace(R.id.rent_viewer, fragment);
fragmentTransaction.addToBackStack(null);
// Commit the transaction
fragmentTransaction.commit();

nested fragments at ActionBar switching

I use ActionBar and use inner TabListener in the Activity:
public static class TabListener<T extends Fragment>
implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class<T> myClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
// Check if the fragment is already initialized
if (myFragment == null) {
// If not, instantiate and add it to the activity
myFragment = Fragment.instantiate(myActivity, myClass.getName());
myActivity.setTitle( myClass.getName());
ft.add(android.R.id.content, myFragment, myTag);
} else {
// If it exists, simply attach it in order to show it
myActivity.setTitle( myFragment.getClass().getName());
ft.attach(myFragment);
}
Log.i("current fragment", myFragment.getClass().toString());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(myFragment);
}
}
}
I need to switch another Fragment at the current tab from DialogFragment . I do it in common way like this:
Fragment newFragment = new ContactsArchiveFragment();
fragmentTransaction.replace(android.R.id.content, newFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
But when I switch to another tab, my current Fragment(which was switched to) is not detached and displays above. How can I solve this?
Try This..
public void addFragment(Fragment fragment, boolean addToBackStack,
int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(android.R.id.content, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
You can use true first time, then change it to false
addFragment(newfragment, true, FragmentTransaction.TRANSIT_NONE);
I solved my issue, using this. Here's the solution:
public static class TabListener<T extends Fragment>
implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class<T> myClass;
private Fragment mFragment;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
Fragment preInitializedFragment = (Fragment) myActivity.getFragmentManager().findFragmentByTag(myTag);
if (preInitializedFragment == null) {
mFragment = (Fragment) Fragment.instantiate(myActivity, myClass.getName());
ft.add(android.R.id.content, mFragment, myTag);
} else {
ft.attach(preInitializedFragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment preInitializedFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (preInitializedFragment != null) {
ft.detach(preInitializedFragment);
} else if (mFragment != null) {
ft.detach(mFragment);
}
}
}

How to change Actionbar Tab from fragment

i have 3 actionbar tabs home:video:purchase by default home will be selected.I can switch between different tabs where i'm able to replace the fragments.I have a gridview in home fragment on click of any grid cell i'm using the below piece of code to navigate to purchase tab,i'm able to replace the home fragment with purchase fragment but how can change the actionbar tab from home tab to purchase tab?????
FragmentTransaction ft = parentActivity
.getFragmentManager()
.beginTransaction();
ft.replace(R.id.mainLayout,new purchase());
ft.commit();
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.setCustomAnimations(R.animator.fragmentanimatorleft,
R.animator.fragmentanimatorright);
ft.replace(R.id.mainLayout, fragment);
// isSettingClicked = false;
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
try {
ft.remove(fragment);
} catch (Exception e) {
// TODO: handle exception
}
}
}

OnCreate of the replaced Fragment is called Twice. Why?

I am using Fragments as Tabs in my application in an Activity that is extended from FragmnetActivity. I am able to add initial Fragments and then on the basis of my application settings, I am replacing fragments. When I am in the debug mode, I observe that, onCreate and other overriden methods of the very new fragmnet are being called twice. Why so? and How can I restrict them to be called once only.
Following is the way I am using Fragments in my app:
public class FragmentTabs extends FragmentActivity implements OnTabChangeListener {
private FragmentTabHost mTabHost;
private HomeFragment homeFragmnet;
private GroupFragment groupFragment;
private TemplateFragment templateFragment;
private SetingsFragment settingsFragment;
private CalendarViewFragment calendarViewFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fragment_tabs);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
homeFragmnet = new HomeFragment();
groupFragment = new GroupFragment();
templateFragment = new TemplateFragment();
settingsFragment = new SetingsFragment();
calendarViewFragment = new CalendarViewFragment();
mTabHost.setOnTabChangedListener(this);
if (Database.getSharedObject(getApplicationContext()).getAppSettings().getListView() == 1) {
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("", getResources().getDrawable(R.drawable.home_tab)), HomeFragment.class, null);
} else {
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("", getResources().getDrawable(R.drawable.home_tab)), CalendarViewFragment.class, null);
}
mTabHost.addTab(mTabHost.newTabSpec("groups").setIndicator("", getResources().getDrawable(R.drawable.groups_tab)), GroupFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("templates").setIndicator("", getResources().getDrawable(R.drawable.templates_tab)),TemplateFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("settings").setIndicator("", getResources().getDrawable(R.drawable.settings_tab)), SetingsFragment.class, null);
}
#Override
protected void onResume() {
super.onResume();
}
private void showHomeFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent, homeFragmnet);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.disallowAddToBackStack();
ft.commit();
}
private void showGroupsFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent, groupFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.disallowAddToBackStack();
ft.commit();
}
private void showTemplateFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent, templateFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.disallowAddToBackStack();
ft.commit();
}
private void showSettingsFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent, settingsFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.disallowAddToBackStack();
ft.commit();
}
private void showCalendarViewFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent, calendarViewFragment);
ft.disallowAddToBackStack();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onTabChanged(String arg0) {
if (mTabHost.getCurrentTab() == 0) {
if (Database.getSharedObject(getApplicationContext()).getAppSettings().getListView() == 1) {
showHomeFragment();
} else {
showCalendarViewFragment();
}
} else if (mTabHost.getCurrentTab() == 1) {
showGroupsFragment();
} else if (mTabHost.getCurrentTab() == 2) {
showTemplateFragment();
} else if (mTabHost.getCurrentTab() == 3) {
showSettingsFragment();
}
}
Any help is appreciated. Thanks!
I use show() and hide() instead, and it works well.
private void showHomeFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (homeFragmnet.isAdded())
ft.show(homeFragmnet);
else
ft.add(R.id.realtabcontent, homeFragmnet);
if (groupFragment.isAdded()) ft.hide(groupFragment);
if (templateFragment.isAdded()) ft.hide(templateFragment);
if (settingsFragment.isAdded()) ft.hide(settingsFragment);
if (calendarViewFragment.isAdded()) ft.hide(calendarViewFragment);
ft.commit();
}

Categories

Resources