I'm creating an apps to create a Sales Order. It has 1 fragment to show list of Sales Orders (ListFragment), 1 fragment to show Sales Order's form (FormFragment) and inside, there is a viewpager which has 2 fragments: HeaderFragment and ItemsFragment. When I accessed it the first time, it works fine, header and items are showing the input fields. But when I accessed it the second time, header and items are empty.
Here is how I open FormFragment from ListFragment:
public class ListFragment extends Fragment {
ListView listViewSO;
Bundle bundle;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
((MainActivity)getActivity()).getSupportActionBar().setTitle("SO LIST");
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_list_so, container, false);
bundle = getArguments();
listViewSO = root.findViewById(R.id.list_view_so);
listViewSO.setOnItemClickListener(SOListItemClick);
return root;
}
private AdapterView.OnItemClickListener SOListItemClick = new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
SalesOrder salesOrder = (ListFragment.this).adapter.getItem(i);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
bundle.putParcelable("salesorder", salesOrder);
FormFragment FormFragment = new FormFragment();
FormFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragment_container, FormFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
}
This is my FormFragment
public class FormFragment extends Fragment {
Bundle bundle;
SalesOrder salesorder;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
((MainActivity)getActivity()).getSupportActionBar().setTitle("EDIT SO");
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_so_form, container, false);
((MainActivity)getActivity()).drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
((MainActivity)getActivity()).toggle.setDrawerIndicatorEnabled(false);
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bundle = getArguments();
salesorder = bundle.getParcelable("salesorder");
viewPager = (ViewPager) root.findViewById(R.id.view_pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) root.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return root;
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getActivity().getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
adapter.addFragment(new HeaderFragment(), "Header");
adapter.addFragment(new ItemFragment(), "Items");
adapter.addBundle(bundle);
viewPager.setAdapter(adapter);
}
}
This is my adapter:
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsPageAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addBundle(Bundle bundle) {
for(int i = 0; i < mFragmentList.size(); i++) {
mFragmentList.get(i).setArguments(bundle);
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
And lastly, this is my HeaderFragment
public class VisitationSOHeaderFragment extends Fragment {
Bundle bundle;
SalesOrder salesorder;
TextInputLayout textInputSoCode, textInputSoDate;
ProgressBar loading;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_visitation_so_header, container, false);
bundle = getArguments();
salesorder = bundle.getParcelable("salesorder");
loading = root.findViewById(R.id.loading);
textInputSoCode = root.findViewById(R.id.text_input_so_code);
textInputSoDate = root.findViewById(R.id.text_input_so_date);
textInputSoCode.getEditText().setText(salesorder.getSoCode());
textInputSoDate.getEditText().setText(salesorder.getSoDate());
return root;
}
}
How is it happen? Is there something wrong with the viewpager settings? Any help would be much appreciated.
Do not use getActivity().getSupportFragmentManager() to get fragment manager for FragmentPagerAdapter. Just use getChildFragmentManager method instead.
Related
I'm a beginner who learning Android basic course
I want to make 6 fragments that have same structure (only title, image, texts will be different) by using single fragment.
I tried this code but I can see only one fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.fragment_container);
MoviePagerAdapter adapter = new MoviePagerAdapter(getSupportFragmentManager());
mainfragment = new MainFragment();
adapter.addItem(mainfragment);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(6);
}
ViewPager Adapter (in MainActivity)
class MoviePagerAdapter extends FragmentStatePagerAdapter {
public ArrayList<Fragment> items = new ArrayList<Fragment>();
#Override
public Fragment getItem(int position) {
return items.get(position);
}
public MoviePagerAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
public void addItem(Fragment item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
}
MainFragment.java
public class MainFragment extends androidx.fragment.app.Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment, container,
false);
//...
'i want to make 6fragments with datas below '
movieData = new MovieData("title1", "rate1", "grade1");
addData(movieData);
movieData = new MovieData("title2", "rate2", "grade2");
addData(movieData);
movieData = new MovieData("title3", "rate3", "grade3");
addData(movieData);
movieData = new MovieData("title4", "rate4", "grade4");
addData(movieData);
movieData = new MovieData("title5", "rate5", "grade5");
addData(movieData);
movieData = new MovieData("title6", "rate6", "grade6");
addData(movieData);
return rootView;
}
public void addData(MovieData movieData){
Bundle bundle = new Bundle();
bundle.putParcelable("data", movieData);
MainFragment mainFragment = new MainFragment();
mainFragment.setArguments(bundle);
title.setText(movieData.title);
reservation_rate.setText(movieData.getReservation_rate());
grade.setText(movieData.getGrade());
image.setImageResource(R.drawable.image6);
}
}
change your code like this:
public class MainActivity extends AppCompatActivity {
private MoviePagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.fragment_container);
adapter = new MoviePagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(6);
for(int i =0;i<6;i++){
createFrag(i);
}
}
}
private void createFrag(int number) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putInt("NUMBER",number);
fragment.setArguments(args);
adapter.addItem(fragment);
adapter.notifyDataSetChanged();
}
class MoviePagerAdapter extends FragmentStatePagerAdapter {
public ArrayList<Fragment> items = new ArrayList<Fragment>();
#Override
public Fragment getItem(int position) {
return items.get(position);
}
public MoviePagerAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
public void addItem(Fragment item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
}
and change your Fragment like this:
public class MainFragment extends androidx.fragment.app.Fragment {
//1st
private int number;
#Nullable
//this is variant 1 - with static Movie data
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment,
container,
false);
//...
//2d
assert getArguments() != null;
number = getArguments().getInt("NUMBER");
switch (number) {
case 0:
MmovieData movieData1 = new MovieData("title1", "rate1",
"grade1");
addData(movieData1);
break;
case 1:
MmovieData movieData2 = new MovieData("title2", "rate2",
"grade2");
addData(movieData2);
break;
//...
}
return rootView;
}
public void addData(MovieData movieData){
title.setText(movieData.title);
reservation_rate.setText(movieData.getReservation_rate());
grade.setText(movieData.getGrade());
image.setImageResource(R.drawable.image6);
}
}
and this is variant 2 ( with dynamic data and listener)
public class MainFragment extends androidx.fragment.app.Fragment {
//1st
private int number;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment,
container,
false);
//...
//2d
assert getArguments() != null;
number = getArguments().getInt("NUMBER");
return rootView;
}
//some method of listener changed
public void dataChanged(MovieData movieData, int position){
if(number==position){
title.setText(movieData.title);
reservation_rate.setText(movieData.getReservation_rate());
grade.setText(movieData.getGrade());
image.setImageResource(R.drawable.image6);
}
}
I have Recycler view in list income fragment and I want to use the same list income fragment for all my dynamically created tags by updating the data of recycler view according to the tab selected. I have the below code and works fine for the first time and only in first tab it works. When I swipe to 2nd, 3rd and 4th or come back to 1st, it shows empty recycler data. I am struggling with this past 2 days. Help is very much appreciated.
IncomeListTabsFragment.java
public class IncomeListTabsFragment extends Fragment {
private TabLayout branchesTabLayout;
private ViewPager incomeListViewPager;
private BranchAPIService branchAPIService;
private List<Branch> branchesList;
private View view;
private ViewPagerAdapter viewPagerAdapter;
public IncomeListTabsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_income_list_tabs, container, false);
incomeListViewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(incomeListViewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
getBranchesFromAPI();
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPagerAdapter = new ViewPagerAdapter(getFragmentManager());
for (Branch branch: branchesList) {
IncomeListFragment incomeListFragment = IncomeListFragment.newInstance(branch.getId());
viewPagerAdapter.addFrag(incomeListFragment, branch.getName());
}
branchesTabLayout = (TabLayout) view.findViewById(R.id.branchTabLayout);
branchesTabLayout.setupWithViewPager(viewPager);
viewPager.setAdapter(viewPagerAdapter);
}
private List<Branch> getBranchesFromAPI() {
// .......
return branchesList;
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
IncomeListFragment.java
public class IncomeListFragment extends Fragment {
View view;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
TabLayout branchesTabLayout;
ViewPager incomeListViewPager;
public static final String ARG_BRANCH_ID = "branch_id";
private BranchAPIService branchAPIService;
private List<Branch> branchesList;
private int branchId;
public IncomeListFragment() {
// Required empty public constructor
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
((IncomeAdapter) recyclerView.getAdapter()).onSaveInstanceState(outState);
}
public static IncomeListFragment newInstance(int branch_id) {
IncomeListFragment incomeListFragment = new IncomeListFragment();
Bundle args = new Bundle();
args.putInt(ARG_BRANCH_ID, branch_id);
incomeListFragment.setArguments(args);
return incomeListFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_income_list, container, false);
branchId = getArguments().getInt(ARG_BRANCH_ID);
List<IncomeParent> incomeParentTest = ((GlobalVariableHelper) getActivity().getApplicationContext()).getIncomeParents();
recyclerView = (RecyclerView) view.findViewById(R.id.income_list_recycler_view);
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
IncomeAdapter incomeAdapter = new IncomeAdapter(getActivity(), incomeData());
incomeAdapter.setParentClickableViewAnimationDefaultDuration();
incomeAdapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(incomeAdapter);
return view;
}
private List<ParentObject> incomeData() {
//get data for recycler view
return incomeParentObject;
}
}
I have 3 tabs each are sharing a single fragment. But this fragment contains a viewPager. So all the three tabs will have a UI with a viewPager and viewPager have three different fragments. After following the examples available I managed to implement Tab layout with single fragment. But when I tried to implement a viewPager inside this fragment I am facing issue. Tab is not scrolling smoothly and its not moving to third tab. I am also not able to see my viewPager fragment.
Main Fragment with tablayout implementation:
public class DashboardFragment extends android.support.v4.app.Fragment {
Activity mActivity;
private TabLayout tabLayout;
private ViewPager viewPager;
private static final String TAG = "DashboardFragment";
public DashboardFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dashboard_fragment, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
viewPager = (ViewPager)view.findViewById(R.id.viewpager);
tabLayout.addTab(tabLayout.newTab().setText("Yesterday"));
tabLayout.addTab(tabLayout.newTab().setText("Last Week"));
tabLayout.addTab(tabLayout.newTab().setText("This Month"));
setupViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
DashboardTabPagerAdapter adapter = new DashboardTabPagerAdapter(((AppCompatActivity)getActivity()).getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
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) {
}
});
}
}
DashboardPagerAdapter:
public class DashboardTabPagerAdapter extends FragmentStatePagerAdapter {
private int mNoOfTabs;
public DashboardTabPagerAdapter(FragmentManager fm, int tabCount) {
super(fm);
mNoOfTabs=tabCount;
}
#Override
public Fragment getItem(int position) {
DashboardYesterdayFragment fragment = new DashboardYesterdayFragment();
Bundle args = new Bundle();
switch (position) {
case 0:
args.putSerializable(AppConstants.TAB_DASHBOARD_TYPE, AppConstants.TAB_DASHBOARD_YESTERDAY);
break;
case 1:
args.putSerializable(AppConstants.TAB_DASHBOARD_TYPE, AppConstants.TAB_DASHBOARD_LAST_WEEK);
break;
case 2:
args.putSerializable(AppConstants.TAB_DASHBOARD_TYPE, AppConstants.TAB_DASHBOARD_THIS_MONTH);
break;
default:
return null;
}
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return mNoOfTabs;
}
}
TabFragment which contains a childViewPager:
public class DashboardYesterdayFragment extends android.support.v4.app.Fragment {
private String title;
private Bundle bundle;
ViewPager mViewPager;
public DashboardYesterdayFragment(){
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bundle = getArguments();
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dashboard_yesterday_layout, container, false);
mViewPager = view.findViewById(R.id.vpPager);
setupViewPager(mViewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
DashboardViewPagerAdapter adapter = new DashboardViewPagerAdapter( getChildFragmentManager(),bundle);
mViewPager.setAdapter(adapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mViewPager.setPageMargin(24);
}
ChildViewPagerAdapter:
public class DashboardViewPagerAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
private Bundle bundle;
public DashboardViewPagerAdapter(FragmentManager fm, Bundle bundle) {
super(fm);
this.bundle=bundle;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return IncidentsFragment.newInstance(bundle);
case 1:
return VehicleUtilizationFragment.newInstance(bundle);
case 2:
return FleetPerformanceFragment.newInstance(bundle);
default:
return null;
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
}
ChildViewPager first fragment:
public class IncidentsFragment extends Fragment {
private TextView mOverSpeeding,mGeoFence,mIdlingCase,mFuelFilling,mMosetIncidences, mLeastIncidences;
public static IncidentsFragment newInstance(Bundle bundle) {
IncidentsFragment fragmentFirst = new IncidentsFragment();
Bundle args = new Bundle();
args.putBundle("bundle", bundle);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.incident_layout, container, false);
initViews(view);
return super.onCreateView(inflater, container, savedInstanceState);
}
private void initViews(View view) {
mOverSpeeding = (TextView)view.findViewById(R.id.over_speeding_value);
mGeoFence = (TextView)view.findViewById(R.id.geofence_value);
mIdlingCase = (TextView)view.findViewById(R.id.idling_value);
mFuelFilling = (TextView)view.findViewById(R.id.fuel_value);
mMosetIncidences = (TextView)view.findViewById(R.id.vehicle_reg_no);
mLeastIncidences = (TextView)view.findViewById(R.id.least_incidences_value);
}
}
I am confused what is going wrong.
Change this:
DashboardTabPagerAdapter adapter = new DashboardTabPagerAdapter(((AppCompatActivity)getActivity()).getSupportFragmentManager(),tabLayout.getTabCount());
to this:
DashboardTabPagerAdapter adapter = new DashboardTabPagerAdapter(((AppCompatActivity)getActivity()).getChildFragmentManager(),tabLayout.getTabCount());
I am developing an application for retail shops network and
I have a problem with fragments in Android.
Is it possible to launch inside a ListView item click listener
a fragment transaction between ListItem and View Pager
with custom layout of a page ?
Any help would be greatly appreciated. Thank You.
This is my OffersFragment class.
public class OffersFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.offers_fragment, container,
false);
categoriesListView = (ListView) getActivity().findViewById(R.id.offerCategoriesList);
categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("offerItem", position);
OfferByCategoryFragment offerByCategoryFragment = new OfferByCategoryFragment();// here is my viewpager fragment offerByCategoryFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.offerItemFragment, offerByCategoryFragment).commit();
}
});
return rootView;
}
}
This is my ViewPager Fragment
public class OfferByCategoryFragment extends Fragment {
public static final int PAGE_COUNT = 3;
ViewPager pager;
PagerAdapter pagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.offers_category_viewpager, container,
false);
pager = (ViewPager) getActivity().findViewById(R.id.pager);
pagerAdapter = new OffersCategoryFragmentPagerAdapter(getFragmentManager());
pager.setAdapter(pagerAdapter);
return rootView;
}
private class OffersCategoryFragmentPagerAdapter extends FragmentPagerAdapter {
public OffersCategoryFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return null;
}
#Override
public int getCount() {
return 0;
}
}
}`
This is my view pager item fragment
public class OfferItemFragment extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
static final String SAVE_PAGE_NUMBER = "save_page_number";
int pageNumber;
public static OfferItemFragment newInstance(int page) {
OfferItemFragment pageFragment = new OfferItemFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
private ImageView offerProductImageView;
private TextView offerProductTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
int savedPageNumber = -1;
if (savedInstanceState != null) {
savedPageNumber = savedInstanceState.getInt(SAVE_PAGE_NUMBER);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.offer_item,null);
offerProductImageView = (ImageView) getActivity().findViewById(R.id.offerImage);
offerProductTextView = (TextView) getActivity().findViewById(R.id.offerText);
return view;
}
}
In my application I want to put a ListView in the first Fragment and I want to move to a new Fragment when I clicked on an item such that each item has its own details
in my code.
I implemented it to move to another Activity, but now my manager says it must go to another Fragment instead of other activity. I'm new to the Fragment world and I don't know how to do this. The manager says that I can use the list fragment but I have not found any useful code.
This my code:
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
static ProgressDialog pd ;
ViewPager mViewPager;
List<Fragment> fragments ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentThree.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFour.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFive.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentSix.class.getName()));
mSectionsPagerAdapter=new SectionsPagerAdapter(super.getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
pd = new ProgressDialog(this);
mViewPager.setAdapter(mSectionsPagerAdapter);
//
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int _pos = position % 6;
return fragments.get(_pos);
}
#Override
public int getCount() {
// Show 3 total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
final String title_section4="Section4";
final String title_section5="Section5";
final String title_section6="Section6";
final String title_section1="Section1";
final String title_section2="Section2";
final String title_section3="Section3";
Locale l = Locale.getDefault();
switch (position) {
case 0:
return title_section1.toUpperCase(l);
case 1:
return title_section2.toUpperCase(l);
case 2:
return title_section3.toUpperCase(l);
case 3:
return title_section4.toUpperCase(l);
case 4:
return title_section5.toUpperCase(l);
case 5:
return title_section6.toUpperCase(l);
}
return null;
}
}
public static class FragmentOne extends Fragment {
ArrayList< String > ar;
ArrayAdapter< String > ad ;
ListView lv ;
TextView tv;
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one, container, false);
tv = (TextView) rootView.findViewById(R.id.mywidget);
tv.setSelected(true);
ar = new ArrayList<String>();
lv = (ListView) rootView.findViewById(R.id.listView1);
for (int i = 0 ; i< 10 ; i++){
ar.add("My Item " + String.valueOf(i));
}
ad = new ArrayAdapter<String>
(getActivity().getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
ar);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast t = Toast.makeText(getActivity(), "Message",
Toast.LENGTH_SHORT);
t.show();
Intent i = new Intent(getActivity(), tst.class);
startActivity(i);
}
});
return rootView;
}
}
public static class FragmentTwo extends Fragment {
public FragmentTwo() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.two, container, false);
return rootView;
}
}
public static class FragmentThree extends Fragment {
public FragmentThree() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.three, container, false);
return rootView;
}
}
public static class FragmentFour extends Fragment {
public FragmentFour() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.four, container, false);
return rootView;
}
}
public static class FragmentFive extends Fragment {
public FragmentFive() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.five, container, false);
return rootView;
}
}
public static class FragmentSix extends Fragment {
public FragmentSix() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.six, container, false);
return rootView;
}
}
}
You have to replace the fragment using Transaction
See here:
http://developer.android.com/guide/components/fragments.html#Example
Check the showDetails(int index) method of TitlesFragment class:
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Use pager and give integer index to each fragment then use following code in itemclick
ViewPager pager;
pager.setCurrentItem(index, true);