Android Fragment内容丢失

时间:2014-10-14 11:50:08

标签: android eclipse android-fragments android-viewpager

我在android eclipse上有一个问题,在viewpager中有片段。当家庭活动开始时,我会在屏幕上显示操作栏标签和第一个片段。当我滑动到下一个片段然后再回到第一个片段时,第一个片段内容仍在屏幕上。但另一方面,如果向右滑动2次并返回第一个片段,其内容将丢失并显示空白屏幕。我的代码如下。如何保留每个片段内容显示或可见?任何帮助表示赞赏。提前完成。

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

}

}

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ğı yenileniyor..");
        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();
    }
}

}

1 个答案:

答案 0 :(得分:0)

尝试使用

setRetainInstance(true);

在oncreate()片段