Содержание фрагмента Android

У меня проблема в eclipse для Android с фрагментами в viewpager. Когда начинается домашняя активность, я показываю вкладки панели действий и первый фрагмент на экране. Когда я перебираю следующий фрагмент, а затем возвращается к первому фрагменту, содержимое первого фрагмента по-прежнему находится на экране. Но, с другой стороны, если проведите 2 раза вправо и верните первый фрагмент, его содержимое будет потеряно и будет показан пустой экран. Мои коды ниже. Как сохранить содержимое каждого фрагмента либо он отображается, либо отображается? любая помощь приветствуется. Thanx заранее.

HomeActivity.java

public class HomeActivity extends FragmentActivity implements TabListener {

private String[] menuItems = null;
private ActionBar bar = null;
private ViewPager viewPager = null;
private TabsAdapter tabsAdapter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_home);
 viewPager = (ViewPager) findViewById(R.id.viewPager);
 viewPager.setPageMargin(10);
 menuItems = getResources().getStringArray(R.array.menuTitles);
 bar = getActionBar();
 bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 tabsAdapter = new TabsAdapter(this, viewPager);
 for (int i = 0; i < menuItems.length; i++) {
 switch (i) {
 case 0:
 tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
 NewsFeedActivity.class, null);
 break;
 case 1:
 tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
 NotificationActivity.class, null);
 break;
 case 2:
 tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
 NewsFeedActivity.class, null);
 break;
 case 3:
 tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
 NotificationActivity.class, null);
 break;
 case 4:
 tabsAdapter.addTab(bar.newTab().setText(menuItems[i]),
 NewsFeedActivity.class, null);
 break;
 default:
 break;
 }
 }

 if (savedInstanceState != null) {
 bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
 }


}

@Override
protected void onSaveInstanceState(Bundle outState) {
 super.onSaveInstanceState(outState);
 outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
 super.onRestoreInstanceState(savedInstanceState);
 // Restore selected tab
 int saved = savedInstanceState.getInt("tab", 0);
 if (saved != getActionBar().getSelectedNavigationIndex())
 getActionBar().setSelectedNavigationItem(saved);
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {

}

public static class TabsAdapter extends FragmentPagerAdapter implements
 ActionBar.TabListener, ViewPager.OnPageChangeListener {

 private final Context mContext;
 private final ActionBar mActionBar;
 private final ViewPager mViewPager;
 private final ArrayList<tabinfo> mTabs = new ArrayList<tabinfo>();

 static final class TabInfo {
 private final Class<!--?--> clss;
 private final Bundle args;

 TabInfo(Class<!--?--> _class, Bundle _args) {
 clss = _class;
 args = _args;
 }
 }

 public TabsAdapter(FragmentActivity activity, ViewPager pager) {
 super(activity.getSupportFragmentManager());
 mContext = activity;
 mActionBar = activity.getActionBar();
 mViewPager = pager;
 mViewPager.setAdapter(this);
 mViewPager.setOnPageChangeListener(this);
 }

 public void addTab(ActionBar.Tab tab, Class<!--?--> clss, Bundle args) {
 TabInfo info = new TabInfo(clss, args);
 tab.setTag(info);
 tab.setTabListener(this);
 mTabs.add(info);
 mActionBar.addTab(tab);
 notifyDataSetChanged();

 }

 @Override
 public void onPageScrollStateChanged(int state) {

 }

 @Override
 public void onPageScrolled(int position, float positionOffset,
 int positionOffsetPixels) {

 }

 @Override
 public void onPageSelected(int position) {
 mActionBar.setSelectedNavigationItem(position);
 }

 @Override
 public void onTabReselected(Tab tab, FragmentTransaction ft) {
 Toast.makeText(mContext, "Reselected!", Toast.LENGTH_SHORT).show();
 Object tag = tab.getTag();
 for (int i = 0; i < mTabs.size(); i++) {
 if (mTabs.get(i) == tag) {
 mViewPager.setCurrentItem(i);
 }
 }
 }

 @Override
 public void onTabSelected(Tab tab, FragmentTransaction ft) {
 Toast.makeText(mContext, "gokay!", Toast.LENGTH_SHORT).show();
 Object tag = tab.getTag();
 for (int i = 0; i < mTabs.size(); i++) {
 if (mTabs.get(i) == tag) {
 mViewPager.setCurrentItem(i);
 }
 }
 }

 @Override
 public void onTabUnselected(Tab tab, FragmentTransaction ft) {

 }

 @Override
 public Fragment getItem(int position) {
 TabInfo info = mTabs.get(position);
 return Fragment.instantiate(mContext, info.clss.getName(),
 info.args);
 }

 @Override
 public int getCount() {
 return mTabs.size();
 }

}
</tabinfo></tabinfo>

}

NewsFeedActivity.java

public class NewsFeedActivity extends Fragment {

static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
private ArrayList<string> xmlList = null;
private XMLParser parser = null;
private String xml = "";
private Document doc = null;
private NodeList nl = null;
private View view = null;
private Element e = null;
private ListView listNewsFeed = null;
private static Bundle args = null;
private static NewsFeedActivity newsFeed = null;
private ArrayAdapter<string> adapter = null;

public static NewsFeedActivity newInstance(int page, String title) {
 newsFeed = new NewsFeedActivity();
 args = new Bundle();
 args.putInt("Page", page);
 args.putString("newsFeed", title);
 newsFeed.setArguments(args);
 return newsFeed;
}

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 view = inflater.inflate(R.layout.activity_news_feed, container, false);
 if (getActivity().getActionBar().getSelectedTab().getPosition() == 0) {
 new NewsFeeder().execute("");
 }
 return view;
}

private class NewsFeeder extends AsyncTask<string, string,="" string=""> {
 private ProgressDialog mProgressDialog = null;

 @Override
 protected void onPreExecute() {
 super.onPreExecute();
 mProgressDialog = new ProgressDialog(getActivity());
 mProgressDialog.setMessage("Haber kaynağı ***********..");
 mProgressDialog.setCancelable(false);
 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
 mProgressDialog.show();
 }

 @Override
 protected String doInBackground(String... params) {
 xmlList = new ArrayList<string>();
 try {
 parser = new XMLParser();
 xml = parser.getXmlFromUrl(URL); // getting XML
 Log.i("gokay", xml);
 doc = parser.getDomElement(xml); // getting DOM element
 nl = doc.getElementsByTagName(KEY_ITEM);
 return null;
 } catch (Exception e) {
 e.printStackTrace();
 System.out.println(e.getMessage());
 Log.e("gokay", e.getMessage());
 return null;
 }
 }

 @Override
 protected void onPostExecute(String result) {
 super.onPostExecute(result);
 mProgressDialog.dismiss();
 for (int i = 0; i < nl.getLength(); i++) {
 e = (Element) nl.item(i);
 xmlList.add(parser.getValue(e, KEY_ID));
 xmlList.add(parser.getValue(e, KEY_NAME));
 xmlList.add("Rs." + parser.getValue(e, KEY_COST));
 xmlList.add(parser.getValue(e, KEY_DESC));
 }

 listNewsFeed = (ListView) view.findViewById(R.id.listView1);
 adapter = new ArrayAdapter<string>(getActivity(),
 android.R.layout.simple_list_item_1, xmlList);
 listNewsFeed.setAdapter(adapter);
 // onFoodMenuItemsDBAddFinished();
 }
}
</string></string></string,></string></string>

}

1 ответ

попробуйте использовать

setRetainInstance(true);

в фрагменте oncreate()

licensed under cc by-sa 3.0 with attribution.