13

我面临以下问题:在主屏幕中,我有 3 个按钮:配置、主要、设置。

  • 单击每个按钮时,将显示相应的片段以在 FrameLayout 中膨胀布局。
  • 当用户处于 Config 或 Setting Fragment 时,可以使用 onBackpressed 或单击 Main 按钮返回主 Fragment。当用户在主片段中时,如果用户单击返回,则会显示一个弹出窗口以确认退出。

在主片段中,我放了一个查看器。在这个 viewpager 中,我放了另外 2 个片段,每个片段都包含一个图像网格(我还使用了一个圆形指示器来查看底部的页面变化)。为简单起见,Config Fragment 和 Setting Fragment 仅在中心显示一个文本。当应用程序启动时,在正常显示主要片段,当我点击按钮设置或配置时,它正常显示相应的片段。问题是当单击后退按钮(在 Android 上)时,它会返回到主片段,但在 viewpager 中没有片段。它显示空屏幕。

显示了 viewpager 中的主要片段 - 片段 1 主要片段 - 显示 viewpager 中的片段 2 配置片段 设置片段 从配置/设置片段返回主片段

当进程从配置/设置片段返回到主片段时,也许我错了。如果主片段只是在没有 viewpager 的情况下膨胀某个布局,则不会发生此问题。从配置/设置片段返回主片段时如何恢复viewpager的状态?我附上我的代码,以便您可以给我更明确的答案。非常感谢您的任何回答。

package com.example.testfragmentviewpager;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;

import com.example.viewpageindicator.CirclePageIndicator;
import com.example.viewpageindicator.PageIndicator;

public class MainActivity extends FragmentActivity {

    Fragment configFragment;
    Fragment settingFragment;
    Fragment mainItemsFragment;
    FrameLayout frmLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);

        if (savedInstanceState == null) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            frmLayout = (FrameLayout) findViewById(R.id.frame_cotainer);
            mainItemsFragment = new MainItemsFragment();
            ft.add(R.id.frame_cotainer, mainItemsFragment, "mainItems").commit();
        }

        addListener(R.id.btnConfig);
        addListener(R.id.btnMain);
        addListener(R.id.btnSetting);

    }

    public void addListener(int buttonID) {
        final Button btn = (Button) findViewById(buttonID);
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showFragment(btn);
            }
        });
    }

    public void showFragment(View v) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        switch (v.getId()) {
            case R.id.btnConfig:
                if (configFragment == null) {
                    configFragment = new ConfigListFragment();
                }
                else if (configFragment.isVisible())
                    return;
                if (getCurrentEntriesInBackStack() == 0) {
                    ft.addToBackStack("mainItems");
                }
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                ft.replace(R.id.frame_cotainer, configFragment, "config");

                break;
            case R.id.btnMain:
                if (mainItemsFragment == null)
                    mainItemsFragment = new MainItemsFragment();
                if (getCurrentEntriesInBackStack() == 0)
                    return;
                else {
                    if (configFragment != null && configFragment.isVisible()) {
                        ft.detach(configFragment);
                        configFragment = null;
                    }
                    if (settingFragment != null && settingFragment.isVisible()) {
                        ft.detach(settingFragment);
                        settingFragment = null;
                    }
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    removeFromContainer(ft);
                    callPopBackStack();
                    return;
                }
            case R.id.btnSetting:
                if (settingFragment == null)
                    settingFragment = new SettingFragment();
                else if (settingFragment.isVisible())
                    return;
                if (getCurrentEntriesInBackStack() == 0) {
                    ft.addToBackStack("mainItems");
                }
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                ft.replace(R.id.frame_cotainer, settingFragment, "setting");
                break;
            default:
                break;
        }

        ft.commit();
    }

    private int getCurrentEntriesInBackStack() {
        FragmentManager fm = getSupportFragmentManager();
        return fm.getBackStackEntryCount();
    }

    private boolean callPopBackStack() {
        FragmentManager fm = getSupportFragmentManager();

        boolean result = fm.popBackStackImmediate();
        return result;
    }

    private void removeFromContainer(FragmentTransaction ft) {
        if (configFragment != null && configFragment.isVisible()) {
            ft.detach(configFragment);
            configFragment = null;
        }
        if (settingFragment != null && settingFragment.isVisible()) {
            ft.detach(settingFragment);
            settingFragment = null;
        }
        ft.commit();
    }

    public static class ConfigListFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.layout_config, container, false);
            return v;
        }
    }

    public static class SettingFragment extends Fragment {
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.layout_setting, container, false);
            return v;
        }

    }

    public static class MainItemsFragment extends Fragment {

        private MyPagerAdapter adapter;
        private ViewPager viewpager;
        private PageIndicator mIndicator;
        View rootView;

        private class setAdapterTask extends AsyncTask<Void, Void, Void> {
            protected Void doInBackground(Void... params) {
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                viewpager.setAdapter(adapter);
                mIndicator = (CirclePageIndicator) rootView.findViewById(R.id.indicator);
                mIndicator.setViewPager(viewpager);

                viewpager.setCurrentItem(0);

            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.mainscreen_layout, container, false);

            adapter = new MyPagerAdapter(getFragmentManager());
            viewpager = (ViewPager) rootView.findViewById(R.id.myviewpager);
            new setAdapterTask().execute();
            return rootView;
        }

    }

    public static class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int index) {
            if (index == 0) {
                return new MainFragment1();
            }
            else {
                return new MainFragment2();
            }
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

    @Override
    public void onBackPressed() {

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        removeFromContainer(ft);
        if (fm.popBackStackImmediate()) {
            return;
        }

        else {

            AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.this);
            dlg.setTitle("Confirm Exit");
            dlg.setMessage("Do you want to exit?").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.this.finish();
                }

            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog alertDlg = dlg.create();
            alertDlg.show();
        }
    }

}
4

1 回答 1

18

看起来您正在使用其中一种旧技巧来嵌入片段。我建议您首先升级到最新的 Android 支持库,即。发布 11 。然后看看如何使用 Child FragmentManager http://developer.android.com/reference/android/support/v4/app/Fragment.html#getChildFragmentManager()

我在 github 上有一个关于如何使用 viewpager 嵌套片段的示例。
https://github.com/marsucsb/nested-fragments

于 2012-12-15T02:01:53.353 回答