I am developing an ExpenseManager app in android, where I am implementing a fragmentActivity. This fragment shows the account summary page with details such as Account Balance, Account Last Transaction Amount and other details.
The AccountSummary Activity is a multi tab activity implemented with ViewPager, ActionBar, FragmentPageAdapter and FragmentActivity.
The layout of summary page will be common for all the accounts and only the data will get changed depending which account user has selected.
Now, I want to implement this activity where I can reuse/ duplicate the same fragment layout (not the instance) across all the accounts or (ActionBar Tabs). When the user selects any tab from actionBar, it should load/show/display a fragment along with that account data.
(I understand that I need to create dynamic Fragment with different TagName and need to replace with the help of FragmentTransaction; for some reason, this solution doesn't work).
This is similar to the application on playstore with the App layout as Url
Could someone post a solution by using an example code ? I've been struggling to find a solution, but nothing seems to work.
EDIT
AccountSummaryTabActivity.java
public class AccountSummaryTabActivity extends FragmentActivity implements ActionBar.TabListener {
ViewPager viewPager = null;
ActionBar actionBar = null;
AccountSummaryTabAdapter accSummaryAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_summary_tab);
DBHelper dbHelper = new DBHelper(getApplicationContext());
RuntimeExceptionDao<Account, Integer> simpleAccountDao = dbHelper.getSimpleAccountDataDao();
List<Account> accountList = simpleAccountDao.queryForAll();
viewPager = (ViewPager)findViewById(R.id.accountSummaryPager);
actionBar = getActionBar();
accSummaryAdapter = new AccountSummaryTabAdapter(getSupportFragmentManager());
accSummaryAdapter.setCount(accountList.size());
viewPager.setAdapter(accSummaryAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String[] accountNameArr = new String[accountList.size()];
Integer i=1;
for (Account account : accountList) {
if(account.getIsPrimaryAcc().equalsIgnoreCase("Y"))
accountNameArr[0] = account.getName();
else
accountNameArr[i++] = account.getName();
}
// Adding Tabs
for (String accountName : accountNameArr) {
actionBar.addTab(actionBar.newTab().setText(accountName).setTabListener(this));
}
Intent intent = getIntent();
if(intent.getStringExtra("selectedAccNameTab")==null)
intent.putExtra("selectedAccNameTab", accountNameArr[0]);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
actionBar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
System.out.println("onTabSelected "+tab.getText());
DBHelper dbHelper = new DBHelper(getApplicationContext());
RuntimeExceptionDao<Account, Integer> simpleAccountDao = dbHelper.getSimpleAccountDataDao();
List<Account> accountList = simpleAccountDao.queryForAll();
Intent intent = getIntent();
intent.putExtra("selectedAccNameTab", tab.getText());
accSummaryAdapter = new AccountSummaryTabAdapter(getSupportFragmentManager());
accSummaryAdapter.setCount(accountList.size());
viewPager.setAdapter(accSummaryAdapter);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
System.out.println("onTabUnselected "+tab.getText());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
System.out.println("onTabReselected "+tab.getText());
}
}
AccountSummaryTabAdapter.java
public class AccountSummaryTabAdapter extends FragmentPagerAdapter {
FragmentManager fm=null;
Integer count = 0;
public AccountSummaryTabAdapter(FragmentManager fm) {
super(fm);
this.fm=fm;
}
public void setCount(Integer count){
this.count=count;
}
#Override
public Fragment getItem(int arg0) {
switch (arg0){
default :{
AccountSummaryFragment fragment = new AccountSummaryFragment();
return fragment;
}
}
}
#Override
public int getCount() {
return count;
}
}
AccountSummaryFragment.java
public class AccountSummaryFragment extends Fragment {
public AccountSummaryFragment() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_account_summary, container, false);
String accountName = getActivity().getIntent().getStringExtra("selectedAccNameTab");
DBHelper dbHelper = new DBHelper(getActivity());
RuntimeExceptionDao<Account, Integer> simpleAccountDao = dbHelper.getSimpleAccountDataDao();
List<Account> accountList = simpleAccountDao.queryForEq("name", accountName);
Account defaultAcc = accountList.get(0);
String[] accountNameArr = new String[]{"Monthly","Quaterly","Half Yearly","Yearly"};
TextView balanceTxVw = (TextView) rootView.findViewById(R.id.accountBalanceTxVw);
Double balance = defaultAcc.getBalance();
DecimalFormat df = new DecimalFormat("0.00");
balanceTxVw.setText(df.format(balance));
Spinner dropdown = (Spinner)rootView.findViewById(R.id.graphSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, accountNameArr);
dropdown.setAdapter(adapter);
return rootView;
}
}
activity_account_summary_tab.xml Layout file
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/accountSummaryPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
Thanks in advance
The most likely way to solve this problem is to do the following:
Since you have the same layout for most of the accounts;
You can indeed use the same fragment but then you should keep track of which tab is selected.
That tab (int) will be passed back to the TabsPagerAdapter. Next;
Based on that integer value, you should return the same fragment but with a different Extra value - for instance say tab 2.
Inside onAttach of your fragment, you can getArguments() or extras and switch on it to get the correct data for that particular fragment.
After using that particular integer to get the correct values, you can assign values to the class variables - that implies that you should make them class-level variables.
I hope that helps a bit. Let me know how it goes.
Related
So I am trying to have a screen with three fragments in different tabs, and on one of them have them switch to be another fragment, but I am unable to figure out how I could do this. I have looked at other similar questions, however, I cannot seem to get them working. So if someone could help me exactly figure it out that would be great.
My tabsadapter is this
public class Tabsadapter extends FragmentStatePagerAdapter {
private int TOTAL_TABS = 3;
public Tabsadapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new fragment1();
case 1:
return new fragment2();
case 2:
return new fragment3();
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return TOTAL_TABS;
}
}
and my main is this:
public class main extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener {
private ViewPager tabsviewPager;
private ActionBar mActionBar;
private Tabsadapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsviewPager = (ViewPager) findViewById(R.id.tabspager);
mTabsAdapter = new Tabsadapter(getSupportFragmentManager());
tabsviewPager.setAdapter(mTabsAdapter);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab1 = getSupportActionBar().newTab().setText("Month").setTabListener(this);
Tab tab2 = getSupportActionBar().newTab().setText("Week").setTabListener(this);
Tab tab3 = getSupportActionBar().newTab().setText("Day").setTabListener(this);
getSupportActionBar().addTab(tab2);
getSupportActionBar().addTab(tab2);
getSupportActionBar().addTab(tab3);
tabsviewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
getSupportActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
}
#Override
public void onTabSelected(Tab selectedtab, FragmentTransaction arg1) {
tabsviewPager.setCurrentItem(selectedtab.getPosition()); //update tab position on tap
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
}
}
Any help anyone can provide would be greatly appreciated. Thanks!
On Android Studio, you can create automatically the code for this :
Right click on a folder of your project, choose New -> Tabbed Activity.
Choose the navigation style. (ActionBarTabs if I understood you well)
Change other fields if needed
Click finish
You now have a brand new Tabbed Activity to use :)
You can read the generated code if you want to understand how it works.
Please ask me if you need any help.
I am scracthing my head for past 1 day but unable to find the solution.
In mine application there are two tabs under the toolbar
First tab is USER-TAB
the second one is ADMIN-TAB
In both the tabs there are the listView. When a ListItem on the USER-TAB is clicked a dialog appears and user take some action.
Now after this when the ADMIN-TAB is Selected the Admin should get refreshed with new sets of data. But It's not. On selecting the ADMIN-TAB the onResume() method and everyting is getting called but it is not able to update the list.
I wont be able to write the Whole code, I am giving some snippet.
Basically I have taken the code from this link
https://github.com/codepath/android_guides/wiki/Sliding-Tabs-with-PagerSlidingTabStrip
In My Main Activity I have written the OpPageChangeListener.
public class MaterialTab extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_main_sample);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
tabsStrip.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position == 0){
MileUserFragment userFragment = new MileUserFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(userFragment);
ft.attach(userFragment);
ft.commit();
} if(position == 1){
MileAdminFragment adminFragment = new MileAdminFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(adminFragment);
ft.attach(adminFragment);
ft.commit();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
OnPageSelected You can see I am detaching and reattaching the fragment.Everything is working fine. Both Fragments OnResume() are getting called but the List is not getting changed. I don't undrstand why
For additional assistance i am adding snippet one Fragment. Hope this will give some Idea where i might be going wrong
public class MileUserFragment extends Fragment {
#Override
public void onResume() {
super.onResume();
new GetAdminDbTask().execute();
if(!internetUtil.isConnectedToInternet(getActivity())){
mSwipeRefreshLayout.setRefreshing(false);
mSwipeRefreshLayout.setEnabled(false);
}
}
public class GetAdminDbTask extends AsyncTask<Admin, Void, String> {
#Override
protected String doInBackground(Admin... parmas) {
_adminList = shipmentDbHandler.getAllAdmin();
return "";
}
#Override
protected void onPostExecute(String str) {
mAdminAdapter = new AdminAdapter(getActivity(), _adminList);
adminListView.setAdapter(mAdminAdapter);
mAdminAdapter.notifyDataSetChanged();
// Set the refresh Listener to false after the list has been loaded with new set of data
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
if(_adminList.size() > 0 ){
mAdminAdapter = new AdminAdapter(getActivity(), _adminList);
adminListView.setAdapter(mAdminAdapter);
mAdminAdapter.notifyDataSetChanged();
}
}
}
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Tab1", "Tab2" };
private FragmentManager fragmentManager;
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
this.fragmentManager = fm;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
FragmentTransaction ft = null;
if(position == 0){
MileUserFragment userFragment = new MileUserFragment();
return userFragment;
}
if(position == 1){
MileAdminFragment adminFragment = new MileAdminFragment();
return archiveFragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Haah.. Finally i got an answer to after an heck of losing almost 1 and half days. It might be not completely good answer but atleast it is one of the closest I got.
First of all MainActivity.java looks like:
tabs.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
int scrollPosition = 0;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position == 0){
scrollPosition = 0;
}
if(position == 1){
scrollPosition = 1;
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == pager.SCROLL_STATE_IDLE){
if(scrollPosition == 0 && application.isActiveAction()){
viewPagerAdapter.notifyDataSetChanged();
application.setActiveAction(false);
}
if(scrollPosition == 1 && application.isArchiveAction()){
viewPagerAdapter.notifyDataSetChanged();
application.setArchiveAction(false);
}
}
}
});
Now what I have done here is I have set OnPageChangeListener and in this I am keeping track of the position whenever the tabs are changing. For my needs what i have done is i have created two boolean variables and setting it when any content on those tab are changing in Application scope. Now when the contents on one tab has been changed or some Action are done I am calling
viewPagerAdapter.notifyDataSetChanged() // Now this is the real gem
after invoking this it will make a call to the ViewPagerAdapter function
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE; // This will get invoke as soon as you call notifyDataSetChanged on viewPagerAdapter.
}
Also the Point is your ViewPagerAdapter should extend FragmentStatePageAdapter. Now the Point is
PagerAdapter.POSITION_NONE
will not cache the fragment and reload a new fragment for that tab position.
Basic idea is we should not make or retutn PagerAdapter.POSITION_NONE everytime on sliding of tab since it destroys the cached element and reload the fragment which affects UI performance.
So finally the basic thing is always check that whether on calling viewPagerAdapter.notifyDataSetChanged() the function getItemPosition() should also gets invoked. Hope it will help somebody. For better perfomance you can make changes according to your requirement.
I got the needed breakthrough and understanding from this post : #Louth Answer
Remove Fragment Page from ViewPager in Android
Just put
viewPager.setCurrentItem(tab.getPosition());
in your onTabSelected method like:
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) {
}
});
Hello I'm developing an android app using 3 Fragments (Fragment A, B, C) inside viewpager and tabs, the viewpager works fine. The fragment A contains a List View, when the user clicks a item, the app open a Fragment Dialog with information about the item selected. This dialog has a button called "Add to favorites". Now I want to do this when user press button:
close the fragment dialog
show the fragment B inside the view pager
send the information from dialog fragment to fragment B
How can I do this?
This is part of my code:
* MainFragmentActivity * (This works fine)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tube);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentA a = new FragmentA();
Bundle args1 = new Bundle();
args1.putInt(FragmentA.ARG_SECTION_NAME , position + 1);
a.setArguments(args1);
return a;
case 1:
FragmentB b= new FragmentB();
Bundle args2 = new Bundle();
args2.putInt(FragmentB.ARG_SECTION_NAME , position + 2);
b.setArguments(args2);
return b;
case 2:
FragmentC c= new FragmentC();
Bundle args3 = new Bundle();
args3.putInt(FragmentC.ARG_SECTION_NAME , position + 3);
c.setArguments(args3);
return c;
default:
return null;
}
}
This is the Fragment Dialog
* FragmentDialogView *
public class FragmentDialogView extends DialogFragment implements OnClickListener {
private static final int REAUTH_ACTIVITY_CODE = 0;
private String videoId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle mArgs = getArguments();
View view = (View) inflater.inflate(R.layout.fragment_dialog_view, container, false);
//Buttons
Button button = (Button) view.findViewById(R.id.button_one);
button.setOnClickListener(this);
buttonDownload.setOnClickListener(this);
return view;
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_one:
//Here it should show the fragment B inside the viewpager
break;
default:
break;
}
}
}
To dismiss the Dialog include the following in your DialogFragment's class
private Dialog dialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog = new Dialog(getActivity());
return dialog;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_one:
dismiss();
break;
default:
break;
}
}
And create a interface
Create the following Communicator.java
public interface Communicator {
public void respond(int i);
}
Implement this Communicator in your MainAcitvity
And create a instance of this Communicator in your fragment like this
public class FragmentDialogView extends DialogFragment implements OnClickListener {
private Communicator com;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
com = (Communicator) getActivity();
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn:
com.respond(1);
break;
}
}
Whenever you click that button it sends the int to the method which is residing inside the MainActivity
which will look like following
#Override
public void respond(int i) {
// Receive a bundle here
// and pass the corresponding information to the FragmentB
// here i'm receving an int and pass it to the FragmentB as a String
FragmentManager fm = getFragmentManager();
FragmentB fragment = (FragmentB) fm.findFragmentByTag("FragmentB");
fragment.fromMainActivity(""+i);
// If the above the one doesn't work keep the instance as Static and then try
viewPager.invalidate();
pagerAdapter.notifyDataSetChanged();
viewPager.setCurrentItem(1, true);
// Inside the setCuttentItem() method 0 first tab
// 1 second tab
// 2 third tab and so on
}
Here I'm receiving an int . You can use a bundle to pass the corresponding information. This will change the viewPager to show the next tab as well
and keep any simple method insdie the FragmentB like the following
public void fromMainActivity(String sample) {
Toast.makeText(getActivity(), sample, duration).show();
}
I hope this would help :) Happy coding
1.Try this : getDialog().dismiss();
2.As I understood correctly, create a method like this in your fragment ,
public static FirstFragment newInstance(String text){
FirstFragment f= new FirstFragment();
return f;
}
Call it in your button onClick() such as FirstFragment.newInstance("Fragment, Instance 1");
3.Create Interface with the method in your DialogFragment can call to pass any data you want back to Fragment that created said DialogFragment. Also set your Fragment as target such as myFragmentDialog.setTargetFragment(this, 0). Then in dialog, get your target fragment object with getTargetFragment() and cast to interface you created. Now you can pass the data using ((MyInterface)getTargetFragment()).methodToPassData(data).
For more info : link
As i am new to android I stuck to some point while implementing ActionBarTab with swipable viewpager using fragments
I have 3 tabs each with some controls last tab will submit all tabs data to one table
i navigate through next button and with tab change event
using next tab i can set data to Class object using getter/Setter and i submit that class data to DB table for save ..
now i want to call same method while tab change event
method is SetdataToModelClass()
How to call same method on tab change event which is already called on button click event so if user navigate through tabs instead next button and change any data My SetdataToModelClass() is called
SetdataToModelClass is in every fragment,where as my Tab change event is in MainFragmentActivity class so how to call SetdataToModelClass() method on tab change event (i.e want to have communication between MainFragment Act & Fragment)
Code for MainActivity Class is here:
public class TestFragmentTabHost extends FragmentActivity implements TabListener {
ViewPager vp;
ActionBar ab;
SalesActivity sa = new SalesActivity();
SessionManager session = null;
String usrNm = null;
String szImeiId = null;
Spinner spnAECust;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabhost_act);
/* Action Bar Color change on create*/
ActionBar actionBar = getActionBar();
ActionBarColor.setBackgroundColor(actionBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setTitle(Html.fromHtml("<font color=\"white\" face=\"verdana,arial\">" + getString(R.string.air) + "</font>"));
// Session Manager
session = new SessionManager(getApplicationContext());
/* To Get Unique Device id */
TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
szImeiId = TelephonyMgr.getDeviceId(); // Requires READ_PHONE_STATE.
// get User Details from Session
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap = session.getUserDetails();
usrNm = hashMap.get(SessionManager.KEY_USRNM);
vp = (ViewPager) findViewById(R.id.pager);
vp.setAdapter(new MyPageAdapter(getSupportFragmentManager()));
ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = ab.newTab();
tab1.setText("INFO");
tab1.setTabListener(this);
ActionBar.Tab tab2 = ab.newTab();
tab2.setText("PORT");
tab2.setTabListener(this);
ActionBar.Tab tab3 = ab.newTab();
tab3.setText("PACKAGES");
tab3.setTabListener(this);
ab.addTab(tab1);
ab.addTab(tab2);
ab.addTab(tab3);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
vp.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
// For Page adapter
class MyPageAdapter extends FragmentPagerAdapter {
public MyPageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Fragment frgmnt = null;
if (arg0 == 0) {
frgmnt = new InfoFragment();
}else if (arg0 == 1) {
frgmnt = new PortFragment();
}else if (arg0 == 2) {
frgmnt = new PackagesFragment();
}
return frgmnt;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
public void setSalesInfoData(List<String> sales) {
while (sales.size() > 0) {
sa.setCustomerId(Integer.parseInt(sales.get(0).toString()));
sa.setProspectId(Integer.parseInt(sales.get(1).toString()));
sa.setCommodityId(Integer.parseInt(sales.get(2).toString()));
sa.setSpecialNotes(sales.get(3));
sa.setLob(sales.get(4));
DateFormat dt = new DateFormat();
Date crTs = dt;
sa.setCrTs(crTs);
sa.setCrUsr(usrNm);
sa.setDeviceId(szImeiId);
break;
}
}
using method to setdata to Class SalesActivity
change adapter to:
class MyPageAdapter extends FragmentPagerAdapter {
Fragment[] fragments=new Fragment[3];
public MyPageAdapter(FragmentManager fm) {
super(fm);
fragments[0]= new InfoFragment();
fragments[1]= new PortFragment();
fragments[2]= new PackagesFragment();
}
#Override
public Fragment getItem(int arg0) {
return fragments[arg0];
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
And in onTabUnselected get the fragment call the function ex:
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment fragment=adapter.getItem(tab.getPosition());
if(fragment instanceof InfoFragment){
((InfoFragment)fragment).SetdataToModelClass();
}
if(fragment instanceof PortFragment){
((PortFragment)fragment).SetdataToModelClass();
}
if(fragment instanceof PackagesFragment){
((PackagesFragment)fragment).SetdataToModelClass();
}
}
Also make adapter object a class variable ex:
ontside onCreate
MyPageAdapter adapter;
in onCreate
adapter=new MyPageAdapter(getSupportFragmentManager());
vp.setAdapter(adapter);
In my app, I am using FragmentStatePagerAdapter with a ViewPager.
All is working well except that when I am coming from background and the memory was cleaned.
In that case, some of the fragments have disappeared. The disappeared fragments are not visible but do take the hole screen. I can't see anything.
What could cause this?
Thanks!
Possible solution, given the poor problem definition:
The Fragment is being redisplayed after the Activity was recreated. Therefore, the widgets in the view are linked to the previous Activity, and you are not correctly re-inflating the view and re-wiring the widgets (redoing the findByID() commands) in onCreateView().
Any time the Activity is recreated, all Fragments must redo these things in onCreateView().
In onCreate try setting setRetainInstance(true); in the Fragments.
I'm using this code... test this on another file (TestViewPager.java maybe) to see if it work and maybe adapt to your code.
For me... it works like magic :P but... I'm newbie on Android, so maybe you need another code solution (sorry I speak spanish :P)
public class Home_ViewPager extends ActionBarActivity
implements ActionBar.TabListener {
funcionPagerAdapter miPagerAdapter;
ViewPager miViewPager;
public void onCreate(Bundle EstadoInstanciaSalvada){
super.onCreate(EstadoInstanciaSalvada);
setContentView(R.layout.home_viewpager);
miPagerAdapter = new funcionPagerAdapter(getSupportFragmentManager());
miViewPager = (ViewPager) findViewById(R.id.vpContenedor);
miViewPager.setAdapter(miPagerAdapter);
final ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Set a Tab when a Fragment is selected
miViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(actionBar.newTab().setText(R.string.tab1_title).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.tab2_title).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.tab3_title).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.tab4_title).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.tab5_title).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.tab6_title).setTabListener(this));
miViewPager.setCurrentItem(1);
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
miViewPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
}
public static class funcionPagerAdapter extends FragmentPagerAdapter{
public funcionPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int itemCapturado) {
switch(itemCapturado){
case 0: return new fragment_1();
case 1: return new fragment_2();
case 2: return new fragment_3();
case 3: return new fragment_4();
case 4: return new fragment_5();
case 5: return new fragment_6();
default:
Fragment miFragmento = new fragment_1();
return miFragmento;
}
}
#Override
public int getCount() {
return 6;
}
}
public static class fragment_1 extends ListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] arrayDeValores = new String[] { "yourItem1", "yourItem2", "yourItem3", "yourItem4", "yourItem5", "yourItem6"};
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arrayDeValores));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something with the data
}
}
//Others Fragments Here...
}