Replace one fragment to another fragment in the TabHost - android

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();

Related

After two different fragments have been replaced, first fragment is recreated when on pressed back button

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();

Fragments and OnBackPressed

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();
}

Custom adapter for multiple fragments in one tab of ViewPager

I want to want to make ViewPager with each tab containing three fragments. FragmentPagerAdapter only works for one fragment, so I tried my best to make my own custom adapter extending PagerAdapter. Unfortunately, the code I wrote only displays these three Fragments in the first tab and after restarting the app all tabs are blank. I suspect that it has something to do with onSaveInstanceState, but I don't know how to make it properly. Also, I've read that I shouldn't add the fragments to FragmentTransaction in instantiateItem, but I don't know where else I could do it. Could you help me ?
TaskListPagerActivity:
public class TaskListPagerActivity extends AppCompatActivity implements BottomPanelFragment.OnBottomPanelSelectedListener {
private static final String TAG = "TaskListPagerActivity";
private ViewPager mViewPager;
FragmentStacker[] mStacker;
public static Intent newInstance(Context packageContext) {
Intent intent = new Intent(packageContext, TaskListPagerActivity.class);
return intent;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_list_pager);
mStacker = new FragmentStacker[7];
mViewPager = (ViewPager) findViewById(R.id.activity_task_list_pager);
mViewPager.setAdapter(new TaskListPagerAdapter(this));
}
// Interface methods
private class TaskListPagerAdapter extends PagerAdapter {
private FragmentActivity mContext;
public TaskListPagerAdapter(FragmentActivity context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment res;
FragmentManager fm = mContext.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (mStacker[position] == null) {
mStacker[position] = new FragmentStacker();
ft.add(container.getId(), mStacker[position]);
} else {
ft.attach(mStacker[position]);
}
res = mStacker[position];
ft.commit();
return res;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 7;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView()==view;
}
}}
FragmentStacker:
public class FragmentStacker extends Fragment {
Fragment[] fragments = createFragments();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.task_list_activity_fragment, container, false);
FragmentManager fm = getFragmentManager();
Fragment customDateFragment = fm.findFragmentById(R.id.custom_date_fragment_container);
Fragment taskListFragment = fm.findFragmentById(R.id.task_list_fragment_container);
Fragment bottomPanelFragment = fm.findFragmentById(R.id.bottom_panel_container);
FragmentTransaction fragmentTransaction = fm.beginTransaction();
if (customDateFragment == null) {
customDateFragment = fragments[0];
taskListFragment = fragments[1];
bottomPanelFragment = fragments[2];
fragmentTransaction.add(R.id.custom_date_fragment_container, customDateFragment);
fragmentTransaction.add(R.id.task_list_fragment_container, taskListFragment);
fragmentTransaction.add(R.id.bottom_panel_container, bottomPanelFragment);
fragmentTransaction.commit();
} else {
fragmentTransaction.attach(customDateFragment);
fragmentTransaction.attach(taskListFragment);
fragmentTransaction.attach(bottomPanelFragment);
}
return v;
}
private Fragment[] createFragments() {
return new Fragment[]{new CustomDateFragment(), new TaskListFragment(), new BottomPanelFragment()};
}}

Viewpager not working with fragment

My ViewPager is not working correctly. I don't know what's wrong with my code. I am facing some problems with my Fragments:
Basically, I have a Fragment named MyListFragment that has a list and on the click event of list item I move to the second Fragment named FlowersFragment that has a ViewPager with three items(Another three Fragments) in it. And i have a Button in my FlowersFragment and on click of that Button i move to the third screen named WelcomeFragment. now i have a problem :
If i go back to FlowersFragment from WelcomeFragment then it loses some Fragments from ViewPager after some research i got a solution like use childFragmentManager while creating adapter. That is good for my pager all Fragments are now showing correctly in my FlowersFragment Pager. But if I go back to MyListFragment and I click on second or third item of ListFragment its showing me exception with NO ACTIVITY.
Here is my FirstFragment named MyListFragment
public class MyListFragment extends Fragment{
private View view;
private FragmentManager fm;
private FragmentTransaction ft;
private ListView listviewPlaces;
private FloristAdapter adapter;
private ArrayList<FloristItems> items = new ArrayList<FloristItems>();
private FlowersFragment frag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = LayoutInflater.from(getActivity());
view = inflater.inflate(R.layout.fragment_list, container,false);
listviewPlaces = (ListView)view.findViewById(R.id.listviewPlaces);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
for (int i = 0; i < 10; i++) {
FloristItems florist = new FloristItems();
florist.away = "3 miles away";
florist.title = "Florist Flowers";
florist.price = "$45";
items.add(florist);
}
adapter = new FloristAdapter(getActivity().getApplicationContext(), items);
listviewPlaces.setAdapter(adapter);
listviewPlaces.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(frag == null){
frag = new FlowersFragment();
}
handleFragments(frag);
}
});
}
private void handleFragments(Fragment fragment){
fm = getActivity().getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
}
}
Here is my FlowersFragment class that have view pager with containing three fragments:
public class FlowersFragment extends Fragment{
private View view;
private FragmentManager fm;
private FragmentTransaction ft;
private ViewPager pager;
private Button btnSendThatFlower;
private FlowerPagerAdapter pageAdapter;
private WelcomeFragment welcomeFrag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = LayoutInflater.from(getActivity());
view = inflater.inflate(R.layout.fragment_choose_flower_buyer, container,false);
pager = (ViewPager)view.findViewById(R.id.viewpager);
btnSendThatFlower = (Button)view.findViewById(R.id.btnSendThatFlower);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pageAdapter = new FlowerPagerAdapter(getActivity().getSupportFragmentManager());
pager.setAdapter(pageAdapter);
btnSendThatFlower.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(welcomeFrag == null){
welcomeFrag = new WelcomeFragment();
}
handleFragments(welcomeFrag);
}
});
}
private void handleFragments(Fragment fragment){
fm = getActivity().getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
} }
Here is my pager Adapter class:
public class FlowerPagerAdapter extends FragmentPagerAdapter{
private ArrayList<Fragment> pagerItems;
public FlowerPagerAdapter(FragmentManager fm) {
super(fm);
pagerItems = new ArrayList<Fragment>();
pagerItems.add(FlowerImage1.getInstance());
pagerItems.add(FlowerImage2.getInstance());
pagerItems.add(CustomFlowerFragment.getInstance());
}
#Override
public Fragment getItem(int num) {
if (num == 0) {
return new FlowerImage1();
}
else if(num == 1) {
return new FlowerImage2();
}
else{
return new CustomFlowerFragment.getInstance();
}
}
#Override
public int getCount() {
return pagerItems.size();
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
//super.restoreState(state, loader);
}}
FlowerImage1 FlowerImage1 CustomFlowerFragment are fragments with only imageview.
This is my last fragment WelcomeFragment
public class WelcomeFragment extends Fragment{
private View view;
private FragmentManager fm;
private FragmentTransaction ft;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = LayoutInflater.from(getActivity());
view = inflater.inflate(R.layout.fragment_write_note_buyer, container,false);
return view;
}}
when i am pressing back press then its not showing fragments in viewpager but after swipe on view pager its showing only first or sometimes last pager fragment.
I have also faced same issue ended up adding following code inside fragment adapter.
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
//super.restoreState(state, loader);
}
I was also faced with the same problem, but i fixed it by extending "FragmentStatePagerAdapter" instead of FragmentPagerAdapter. for your case,it would be:
public class FlowerPagerAdapter extends FragmentStatePagerAdapter{
private ArrayList<Fragment> pagerItems;
public FlowerPagerAdapter(FragmentManager fm) {
super(fm);
pagerItems = new ArrayList<Fragment>();
pagerItems.add(FlowerImage1.getInstance());
pagerItems.add(FlowerImage2.getInstance());
pagerItems.add(CustomFlowerFragment.getInstance());
}
#Override
public Fragment getItem(int num) {
if (num == 0) {
return new FlowerImage1();
}
else if(num == 1) {
return new FlowerImage2();
}
else{
return new CustomFlowerFragment.getInstance();
}
}
#Override
public int getCount() {
return pagerItems.size();
}
}

Android: ListView detail paging

Here's my setup: I have MainActivity which has the following code:
public class MainActivity extends FragmentActivity {
FragmentList listFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
listFragment = new FragmentList();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.list_container, listFragment);
fragmentTransaction.commit();
}
}
I then have FragmentList, which is a ListView fragment and FragmentDetail, which is the fragment displayed when selecting a particular ListView row.
Here's a snippet of the FragmentList code:
public class FragmentList extends Fragment {
private ListView list;
private FragmentDetail detailFragment;
private long detailId;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// ListView gets set via an adapter
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
detailId = id;
mPager = (ViewPager)getActivity().findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.list_container, detailFragment);
fragmentTransaction.commit();
}
});
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
detailFragment = new FragmentDetail();
Bundle mBundle = new Bundle();
mBundle.putLong("detailId", detailId);
detailFragment.setArguments(mBundle);
return detailFragment;
}
#Override
public int getCount() {
return 5;
}
}
}
And FragmentDetail:
public class FragmentDetail extends Fragment {
private long id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_view, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
id = bundle.getLong("detailId");
// Set views based on id
}
}
Here are my issues:
The line fragmentTransaction.replace(R.id.list_container, detailFragment); in FragmentList errors out saying that I cannot change ID of container. Why is that?
After I comment the line in issue #1 out, the detail fragment loads fine and lets me swipe. However, only one of the detail fragment pages contains any data; the rest are blank. How can I implement the following: say my ListView contains "iOS", "Android", "Windows" rows. When I click on "iOS", it brings up details fragment for iOS. When I swipe to the left, I want "Android" detail fragment to show up; then when I swipe again, "Windows" detail fragment, etc.
Thanks!

Categories

Resources