I'm using one Activity as container for fragments.
There is a problem:
If you open the ProfileEditFragment and press on the back button, then successfully call a method onBackPressed() in MainActivity and then happens next:
1)Open MapFragments past state
2)Open ProfileEditFragment from which we have pressed the back button(for unknown reasons)
I'm tried to use getSupportFragmentManager().popBackStack()but it did not help (there was no reaction to the press back).
I check the contents of the stack before the call onBackPressed() and it's not empty.
MainActivity:
#Override
public void showMapFragment() {
// getSupportFragmentManager().popBackStack(null,getSupportFragmentManager().POP_BACK_STACK_INCLUSIVE);
//mainPresenter.clearActiveLoginFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.ltContainer, MapFragment.newInstance())
.addToBackStack(null)
.commit();
}
#Override
public void showProfileEditFragment() {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.ltContainer, ProfileEditFragment.newInstance())
.addToBackStack(null)
.commit()
;
}
#Override
public void onMainBackStack() {
int count = getSupportFragmentManager().getBackStackEntryCount();
Log.d("COunt in backstack", count + "");
// getSupportFragmentManager().popBackStack();
// Log.d("COunt in backstack",getSupportFragmentManager().popBackStackImmediate()
// +"");
// getSupportFragmentManager().popBackStack();
// getSupportFragmentManager().popBackStackImmediate();
super.onBackPressed();
}
ProfileEditFragment
private static final int LAYOUT = R.layout.fragment_profile_edit;
//#formatter:off
#InjectPresenter ProfileEditPresenter mProfileEditPresenter;
//#formatter:on
public static ProfileEditFragment newInstance() {
ProfileEditFragment fragment = new ProfileEditFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
View view=inflater.inflate(LAYOUT, container, false);
ButterKnife.bind(this,view);
return view;
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
MapFragment
//#formatter:off
#InjectPresenter MapPresenter mapPresenter;
#BindView(R.id.map) ru.yandex.yandexmapkit.MapView mapView;
#BindView(R.id.fbMenu) FloatingActionButton fbMenu;
//#formatter:on
private MapController mapController; //// FIXME: 11.11.2016
public static MapFragment newInstance() {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
View view = inflater.inflate(LAYOUT, container, false);
ButterKnife.bind(this, view);
setupMap();
showMapButtons();
mapPresenter.checkPermission();
setupListeners();
return view;
}
private void setupListeners() {
fbMenu.setOnClickListener(v->mapPresenter.onClickMenu());
}
private void setupMap() {
mapController = mapView.getMapController();
mapController.getMapRotator().a(true);
}
#Override
public void showMapButtons() {
mapView.showZoomButtons(true);
mapView.showScaleView(false);
mapView.showJamsButton(false);
}
#Override
public void showProfileEditFragment() {
((MainActivity) getActivity()).showProfileEditFragment();
}
Related
I have two fragment inside a LinearLayout.
When I click on a FAB button I would like to hide one but a
null object reference appears on FragmentTransaction hide method.
Why doesn't "f" have a view reference?
public class FragmentOne extends Fragment {
public FragmentOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
FloatingActionButton fabTemp = returnView.findViewById(R.id.fabTemp);
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(0).getChildFragmentManager().getFragments().get(1);
final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
fabTemp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
transaction.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
if (f.isHidden()) {
transaction.show(f);
} else {
transaction.hide(f);
}
transaction.commit();
}
});
return returnView;
}
I solved in another way despite not being as i wanted
final View frag = getView().findViewById(R.id.frgSettemp);
frag.setVisibility(View.GONE);
In onCreateView just inflate and return the view.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
return returnView;
}
Try the other processing in onViewCreated #override method. like this
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
FloatingActionButton fabTemp = getView().findViewById(R.id.fabTemp);
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(0);
final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
fabTemp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
transaction.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
if (f.isHidden()) {
transaction.show(f);
} else {
transaction.hide(f);
}
transaction.commit();
}
});
}
Hope this will help.
You should call only
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(0);
or
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(1);
What you have done will return null for sure.
I have problem: A Fragment is not reattached to its hosting ViewPager after returning from another fragment by using popBackStack.
One Activity hosting a Fragment whose layout holds a ViewPager. The ViewPager is populated by a FragmentStateViewPagerAdapter. The Fragment hosted inside the pager can open sub page lists, containing a new set of pages. All works fine as long as the back button is not pressed. As soon as the user closes one of the sub Page the previous Page is recreated, but without the Page that was displayed previously (Empty page with whiteblank page). I have searching but still not resolve my problem.
Full Code of TestProject can be found on Github
MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val ft = supportFragmentManager.beginTransaction()
ft.add(R.id.frameLayout, HomeFragment.newInstance())
ft.commit()
}
}
HomeFragment:
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
TabLayout tabLayout = v.findViewById(R.id.tabLayout);
ViewPager viewPager = v.findViewById(R.id.viewPager);
VPAdapter adapter = new VPAdapter(getFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return v;
}
public static Fragment newInstance() {
return new HomeFragment();
}
}
VPAdapter:
public class VPAdapter extends FragmentStatePagerAdapter{
public VPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TabFragment.newInstance(position);
}
#Override
public CharSequence getPageTitle(int position) {
return "TAB " + position;
}
#Override
public int getCount() {
return 2;
}
}
TabFragment:
public class TabFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TAB", "onCreate");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.e("TAB", "onCreateView");
return inflater.inflate(R.layout.fragment_tab, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle args = getArguments();
if (args != null) {
int tabIndex = args.getInt("tab_index", 0);
TextView tv = view.findViewById(R.id.textView);
tv.setText(String.format(Locale.getDefault(), "TAB FRAGMENT INDEX %d", tabIndex));
}
Button button = view.findViewById(R.id.button);
button.setText("Open Next Fragment");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, LastFragment.newInstance());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("TAB", "onDestroy");
}
public static Fragment newInstance(int index) {
Bundle args = new Bundle();
args.putInt("tab_index", index);
TabFragment tab = new TabFragment();
tab.setArguments(args);
return tab;
}
}
LastFragment:
public class LastFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_last, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getFragmentManager().popBackStack();
}
});
}
public static Fragment newInstance() {
return new LastFragment();
}
}
You have to Use getChildFragmentManager() For Viewpager to adapt Popback Feature.
VPAdapter adapter = new VPAdapter(getChildFragmentManager());
You Can Refer this Documentation on ChildFragmentManager()
I'm working on a flashcard like app and i've been wrestling with the flip animation. I've based my code on the AnimationsDemo from android with the difference being that it is done inside a fragment instead of an activity.
It works fine, not entirely as the preview of the aforementioned demo, but decent enough. Except... after changing orientation.
If the app is started in landscape, it works fine in landscape, but freaks in portrait and if the app is launched in portrait it works in portrait and freaks in landscape.
This is my code ( i skimmed the datamodel obviously)
public class MyFlashCardFragment extends Fragment {
private MyDataModel model;
private Handler mHandler = new Handler();
private boolean mShowingBack = false;
FrameLayout frameLayout;
public static MyFlashCardFragment create(MyDataModel m) {
MyFlashCardFragment fragment = new MyFlashCardFragment();
Bundle bundle = new Bundle();
bundle.putString(AppKeys.FRONT_KEY,m.getFrontText());
bundle.putString(AppKeys.BACK_KEY,m.getBackText());
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!getArguments().isEmpty()) {
model = new MyDataModel();
model.setFrontText(getArguments().getString(AppKeys.FRONT_KEY));
model.setBackText(getArguments().getString(AppKeys.BACK_KEY));
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if (model == null) {
return super.onCreateView(inflater, container, savedInstanceState);
} else {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_flashcard, container, false);
frameLayout = (FrameLayout) root.findViewById(R.id.chilfd_frame);
Button btn_overlay = (Button) root.findViewById(R.id.overlaybutton);
btn_overlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
return root;
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState == null) {
getChildFragmentManager()
.beginTransaction()
.add(R.id.chilfd_frame, CardFrontFragment.create(model.getFrontText()))
.commit();
} else {
mShowingBack = (getChildFragmentManager().getBackStackEntryCount() > 0);
}
getChildFragmentManager().addOnBackStackChangedListener(new android.app.FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
mShowingBack = (getChildFragmentManager().getBackStackEntryCount() > 0);
getActivity().invalidateOptionsMenu();
}
});
}
private void flipCard() {
if (mShowingBack) {
getChildFragmentManager().popBackStack();
return;
}
mShowingBack = true;
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(frameLayout.getId(), CardBackFragment.create(model.getBackText()))
.addToBackStack(null)
.commit();
mHandler.post(new Runnable() {
#Override
public void run() {
getActivity().invalidateOptionsMenu();
}
});
}
/**
* A fragment representing the front of the card.
*/
public static class CardFrontFragment extends Fragment {
String frontText;
public static CardFrontFragment create(String frontText) {
CardFrontFragment fragment = new CardFrontFragment();
Bundle bundle = new Bundle();
bundle.putString(AppKeys.FRONT_KEY,frontText);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!getArguments().isEmpty()) {
frontText = getArguments().getString(AppKeys.FRONT_KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (TextUtils.isEmpty(frontText)) {
return super.onCreateView(inflater, container, savedInstanceState);
} else {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_flashcard_front, container, false);
((TextView) rootView.findViewById(R.id.tv_name)).setText(frontText);
return rootView;
}
}
}
/**
* A fragment representing the back of the card.
*/
public static class CardBackFragment extends Fragment {
String backText;
public static CardBackFragment create(String backText) {
CardBackFragment fragment = new CardBackFragment();
Bundle bundle = new Bundle();
bundle.putString(AppKeys.BACK_KEY,backText);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!getArguments().isEmpty()) {
backText = getArguments().getString(AppKeys.BACK_KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (TextUtils.isEmpty(backText)) {
return super.onCreateView(inflater, container, savedInstanceState);
} else {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_flashcard_back, container, false);
((TextView) rootView.findViewById(R.id.tv_name)).setText(backText);
return rootView;
}
}
}
}
The parentfragment is loaded form a viewpager:
pager = (ViewPager) findViewById(R.id.pager);
adapter = new FlashCardPageAdapter(getFragmentManager(), getAllFrom(ref));
pager.setAdapter(adapter);
pager.setCurrentItem(position,true);
pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
}
});
and the adapter used is:
public class FlashCardPageAdapter extends FragmentStatePagerAdapter {
private ArrayList<MyDataModel> Models;
public FlashCardPageAdapter(FragmentManager fm, ArrayList<MyDataModel> list) {
super(fm);
this.Models = list;
}
#Override
public Fragment getItem(int position) {
return FlashCardFragment.create(Models.get(position));
}
#Override
public int getCount() {
return Models.size();
}
}
I also tried to create the animations form an Animator object and add that to a transparent button and animating views in and out and toggling the visibility and the result is the same.
Any ideas/suggestions would be welcome.
It turns out there's nothing missing in my code and the problem is emulator related. Well at least it seems that way. I tried it on 2 real devices (1 phone/1 tablet) and the problem didn't manifest on them, so might be an AVD bug or simple shortcoming of the simulated orientation change.
I have three fragment and one activity. It works this way:
[activity]-> [MainFragment]->[MenuFragment]->[SignUpFragment]
When [SignUpFragment] is back pressed, the [MainFragment] is created twice.
I tried setRetaInInstance(true) and I checked savedInstanceState but I can not prevent [MainFragment] recreating.
This is my MainActivity:
public class MainActivity extends AppCompatActivity {
public Bundle mSavedInstanceState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedInstanceState = savedInstanceState;
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
callMainFragment();
}
private void callMainFragment() {
if (mSavedInstanceState == null) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_category, new MainFragment(), MainFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
public ActionBar getMainActionBar(){
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Action Bar Display settings
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// Custom view inflater
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Custom layout view
View viewActionBar = inflater.inflate(R.layout.action_bar, null);
// Set custom view
actionBar.setCustomView(viewActionBar);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
}
return actionBar;
}
This is my MainFragment:
public class MainFragment extends BaseFragment implements AdapterView.OnItemClickListener, BuyersGuideCategoriesDelegate, View.OnClickListener {
private Bundle mSavedInstanceState;
private BuyersGuideCategoriesFragment mCategoriesFragment;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
if (mSavedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_main, container, false);
// Call Grid View Buyers Guide Fragment
mCategoriesFragment = new BuyersGuideCategoriesFragment();
mCategoriesFragment.mGridViewDelegate = this;
setIcons();
setTitles();
setTexts();
initListView();
}
return mView;
}
#Override
public void onResume() {
super.onResume();
ImageView menu = (ImageView) ((MainActivity) getActivity()).getMainActionBar().getCustomView().findViewById(R.id.action_bar_menu_icon);
menu.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mSavedInstanceState == null) {
MainActivity activity = (MainActivity) getActivity();
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_category, new MenuFragment(),MenuFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
}
This is my MenuFragment:
public class MenuFragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private Bundle mSavedInstanceState;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
if (savedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_menu, container, false);
setMenuItemsListViewAdapter();
}
return mView;
}
private void setMenuItemsListViewAdapter() {
ListView menuItems = (ListView) mView.findViewById(R.id.list_menu_items);
ListMenuItemsListViewAdapter adapter = new ListMenuItemsListViewAdapter(getContext(),getMenuItemNames());
menuItems.setAdapter(adapter);
menuItems.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch ((String) parent.getAdapter().getItem(position)){
case SIGN_UP:
replaceFragment(R.id.container_category,new SignUpFragment(),SignUpFragment.class.getSimpleName());
break;
}
}
private void replaceFragment(int containerId,Fragment fragment, String fragmentTag){
if (mSavedInstanceState == null){
MainActivity activity = (MainActivity) getActivity();
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(containerId,fragment,fragmentTag);
transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.menu_back_icon:
replaceFragment(R.id.container_category, new MainFragment(),MainFragment.class.getSimpleName());
break;
}
}
}
And this is my SignUpFragment:
public class SignUpFragment extends BaseFragment implements View.OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_sign_up, container, false);
}
return mView;
}
}
EDIT 1: The MainFragment is recreated only when I return from SignUpFragment to MenuFragment. I am doing wrong using so many fragments? Should I use activity?
When you are move between Fragments, call addToBackStack() :
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace( R.id.fragment, new MyFragment() ).addToBackStack( "ftransaction" ).commit();
Create first Fragment:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.add(R.id.container, new FirstFragment()).addToBackStack(null).commit();
Second:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace(R.id.container, new SecondFragment()).addToBackStack(null).commit();
and Third:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace(R.id.container, new ThirdFragment()).commit();
I am creating a five tabs that contains one fragment each.
I am using ListView in the first tab and in the ListView OnItemClickListener I want to replace from the first Tab Fragment to second tab Fragment.
How can I do that by using Fragment and TabHost?
I extends Fragment for main class and all fragment classes. I am not extends FragmentActivity. So how can I change the tab from one fragment to another fragment?
MainClass:
public class TabsFragment extends Fragment implements OnTabChangeListener {
private View mRoot;
public TabHost mTabHost;
private int mCurrentTab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.tabs_fragment, null);
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
// manually start loading stuff in the first tab
updateTab("1");
}
private void setupTabs() {
mTabHost.setup(); // important!
mTabHost.addTab(newTab("1", R.drawable.fragment1, R.id.fragment1));
mTabHost.addTab(newTab("2", R.drawable.fragment2, R.id.fragment2));
mTabHost.addTab(newTab("3", R.drawable.fragment3, R.id.fragment3));
mTabHost.addTab(newTab("4", R.drawable.fragment4, R.id.fragment4));
mTabHost.addTab(newTab("5", R.drawable.fragment5, R.id.fragment5));
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View indicator = LayoutInflater.from(getActivity()).inflate(
R.layout.tab,
(ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
((ImageView) indicator.findViewById(R.id.imageView1)).setImageResource(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onTabChanged(String tabId) {
updateTab(tabId);
mCurrentTab = Integer.valueOf(tabId) - 1;
}
private void updateTab(String tabId) {
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
if (tabId.equals("1"))
fm.beginTransaction().replace(R.id.fragment1, new Fragment1(), tabId).commit();
else if (tabId.equals("2"))
fm.beginTransaction().replace(R.id.fragment2, new Fragment2(), tabId).commit();
else if (tabId.equals("3"))
fm.beginTransaction().replace(R.id.fragment3, new Fragment3(), tabId).commit();
else if (tabId.equals("4"))
fm.beginTransaction().replace(R.id.fragment4, new Fragment4(), tabId).commit();
else if (tabId.equals("5"))
fm.beginTransaction().replace(R.id.fragment5, new Fragment5(), tabId).commit();
}
}
}
Fragment1:
public class Fragment1 extends Fragment implements OnItemClickListener {
ListView listView;
View theView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
theView = inflater.inflate(R.layout.fragment1, container, false);
listView = (ListView)theView.findViewById(R.id.list);
listView.setOnItemClickListener(this);
return theView;
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
Fragment2 newFragment = new Fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.map, newFragment);
transaction.commit();
}
}
Fragment2:
public class Fragment2 extends SupportMapFragment {
private LatLng mPosFija = new LatLng(37.878901,-4.779396);
GoogleMap mapView;
public Fragment2() {
super();
}
public static Fragment2 newInstance(LatLng posicion) {
Fragment2 frag = new Fragment2();
frag.mPosFija = posicion;
return frag;
}
#Override
public void onResume() {
super.onResume();
initMap();
}
#Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.fragment2, container, false);
view.setId(getId());
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview);
mapView = fm.getMap();
initMap();
return view;
}
private void initMap() {
UiSettings settings = mapView.getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(true);
mapView.addMarker(new MarkerOptions().position(mPosFija).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
}
}
Check out my post. This contains all you need with basic.
Dynamically changing the fragments inside a fragment tab host?
NextFragment nextFrag = new NextFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack("next");
//container_framelayout: FrameLayout of Fragment to be replaced
transaction.replace(R.id.container_framelayout, nextFrag);
transaction.commit();