9

我正在使用操作栏选项卡,因为我需要导航元素出现在每个页面上。我使用 ActionBarSherlock 来实现向后兼容性(最低 API 8,目标 API 17)。我的 MainActivity 扩展了 SherlockFragmentActivity。onCreate()为此,我有

ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

actionBar.setDisplayShowTitleEnabled(true);

Tab tab1 = actionBar.newTab().setText("My Pages")
    .setTabListener(new MyPagesFragment());

Tab tab2 = actionBar.newTab().setText("Search")
    .setTabListener(new SearchFragment());

Tab tab3 = actionBar.newTab().setText("About")
    .setTabListener(new AboutFragment());

// Start with the second tab selected.
actionBar.addTab(tab1, 0, false);
actionBar.addTab(tab2, 1, true);
actionBar.addTab(tab3, 2, false);

所有选项卡片段都是实现的 SherlockListFragmentsActionBar.TabListener并执行此操作

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    ft.replace(android.R.id.content, this, "mypages");
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    ft.remove(this);
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // Force a complete reload.
    onTabSelected(tab, ft);
}

搜索页面有一个 EditText 并在AsyncTask中使用它的值从 API 获取数据并将其添加到 SQLite 数据库,然后再调用

((MainActivity) getActivity()).showDetailView(responseCode);

显示详细信息,这是我的 MainActivity中的一个方法,如下所示:

protected void showDetailView(long codeID) {
    SherlockFragment detailFragment = new DetailFragment();
    Bundle args = new Bundle();
    args.putLong("codeID", codeID);
    detailFragment.setArguments(args);

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(android.R.id.content, detailFragment);
    ft.addToBackStack(null);
    ft.commit();
}

DetailFragment 是用于getArguments()检索 codeID的 SherlockFragment——

Bundle args = getArguments();
if (null != args) {
  codeRowID = args.getLong("codeID");
}

-- 并从数据库中读取匹配的数据进行显示。所述数据通常包含指向更多详细信息的链接,单击该链接会导致使用新的 codeID 再次调用 showDetailView。

MyPages 是所有缓存的详细信息页面的列表,它也调用 showDetailView:

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
  ((MainActivity) getActivity()).showDetailView(pages[position].codeId);
}

展望未来,这似乎工作正常。但是,当我使用后退按钮时,有时碎片会粘在周围,因此它们在恢复的碎片后面仍然可见。我该如何阻止这种情况发生?


我认为问题可能是标签没有被添加到后台?但是当我尝试这样做时,他们会抛出一个异常,告诉我他们不能被添加到后台堆栈,所以我不明白你应该如何处理这个问题。我不明白为什么这个东西,它似乎应该是很多人想做的非常基本的导航东西——后退键一直在我见过的每一部安卓手机和桌子上,无论是物理上的还是软件上的!--显然没有已知的解决方案。我只是从根本上误解了它们的用途吗?在这种情况下不应该使用片段吗?如果不在每个页面上重复相同的代码,你还如何做持久的导航元素?


记录 - 启动应用程序 -

07-20 23:33:49.521: D/NAVIGATION_TRACE(7425): MAIN - onCreate
07-20 23:33:50.013: D/NAVIGATION_TRACE(7425): SEARCH - onTabSelected
07-20 23:33:50.021: D/NAVIGATION_TRACE(7425): SEARCH - onCreateView
07-20 23:33:50.060: D/NAVIGATION_TRACE(7425): SEARCH - onActivityCreated
07-20 23:33:50.060: D/NAVIGATION_TRACE(7425): MAIN - onResume

搜索现在可见。搜索项目以显示详细视图 -

07-20 23:34:52.123: D/NAVIGATION_TRACE(7425): SEARCH - handleResponseCode
07-20 23:34:52.123: D/NAVIGATION_TRACE(7425): MAIN - showDetailView - 31

细节现在可见;搜索不见了。单击我的页面选项卡 -

07-20 23:35:37.787: D/NAVIGATION_TRACE(7425): SEARCH - onTabUnselected
07-20 23:35:37.787: D/NAVIGATION_TRACE(7425): MYPAGES - onTabSelected
07-20 23:35:37.826: D/NAVIGATION_TRACE(7425): MYPAGES - onCreateView
07-20 23:35:37.873: D/NAVIGATION_TRACE(7425): MYPAGES - onActivityCreated

MyPages 现在可见;细节没了。单击返回按钮 -

07-20 23:36:12.130: D/NAVIGATION_TRACE(7425): SEARCH - onCreateView
07-20 23:36:12.201: D/NAVIGATION_TRACE(7425): SEARCH - onActivityCreated

SearchMyPages 现在都显示了。


主要活动:

public class MainActivity extends SherlockFragmentActivity 
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {   
        super.onCreate(savedInstanceState);
        Log.d("NAVIGATION_TRACE", "MAIN - onCreate");

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        actionBar.setDisplayShowTitleEnabled(true);

        Tab tab1 = actionBar.newTab().setText("My Pages")
            .setTabListener(new TabListener<MyPagesFragment>(
            this, "mypages", MyPagesFragment.class));

        Tab tab2 = actionBar.newTab().setText("Search")
            .setTabListener(new TabListener<SearchFragment>(
            this, "search", SearchFragment.class));

        Tab tab3 = actionBar.newTab().setText("About")
            .setTabListener(new TabListener<AboutFragment>(
            this, "about", AboutFragment.class));

        // Start with the second tab selected.
        actionBar.addTab(tab1, 0, false);
        actionBar.addTab(tab2, 1, true);
        actionBar.addTab(tab3, 2, false);
    }

    @Override
    public void onBackPressed()
    {
        FragmentManager fm = getSupportFragmentManager();
        if (0 < fm.getBackStackEntryCount())
        {
            super.onBackPressed();
        } else {
            // prompt to quit
            AlertDialog.Builder alertErrorResponse = new AlertDialog.Builder(this);
            alertErrorResponse.setMessage("Close app?");
            alertErrorResponse.setNegativeButton("Cancel", null);
            alertErrorResponse.setPositiveButton("OK", new DialogInterface.OnClickListener()
            {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                finish();
            }
            });
            alertErrorResponse.show();
        }
    }

    public void showDetailView(long codeID) {
        Log.d("NAVIGATION_TRACE", "MAIN - showDetailView - "+String.valueOf(codeID));
        lastShownCode = codeID;
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        SherlockFragment detailFragment = new DetailFragment();
        Bundle args = new Bundle();
        args.putLong("codeID", codeID);
        detailFragment.setArguments(args);
        ft.replace(android.R.id.content, detailFragment, "details");
        ft.addToBackStack(null);
        ft.commit();
    }

    public class TabListener<T extends SherlockListFragment> implements ActionBar.TabListener
    {
        private final SherlockFragmentActivity mActivity;
        private final String mTag;
        private final Class<T> mClass;
        private SherlockListFragment mFragment;

        public TabListener (SherlockFragmentActivity activity, String tag, Class<T> clz) 
        {
            Log.d("NAVIGATION_TRACE", "TabListener - "+tag+" - "+clz.getCanonicalName());
            mActivity = activity;
            mTag = tag;
            mClass = clz;

            FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
            mFragment = (SherlockListFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null && !mFragment.isDetached()) 
            {
                Log.d("NAVIGATION_TRACE", "DETACH - "+mTag);
                removeDetail(ft);
                ft.detach(mFragment);
            }
            ft.commit();
        }

        public void clearBackStack()
        {
            Log.d("NAVIGATION_TRACE", "clearBackStack - "+mTag);
            FragmentManager fm = mActivity.getSupportFragmentManager();
            if (null != fm && 0 < fm.getBackStackEntryCount())
            {
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) 
        {
            Log.d("NAVIGATION_TRACE", "onTabSelected - "+mTag);

            clearBackStack();

            ft = mActivity.getSupportFragmentManager().beginTransaction();

            if (mFragment == null) 
            {
                Log.d("NAVIGATION_TRACE", "ADD/SHOW - "+mClass.getName());
                removeDetail(ft);
                mFragment = (SherlockListFragment) SherlockListFragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
                ft.commit();
            } 
            else 
            {
                Log.d("NAVIGATION_TRACE", "ATTACH/SHOW - "+mClass.getName());
                removeDetail(ft);
                ft.attach(mFragment);
                ft.show(mFragment);
                ft.commit();
            }

        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) 
        {        
            Log.d("NAVIGATION_TRACE", "onTabUnselected - "+mTag);
            ft = mActivity.getSupportFragmentManager().beginTransaction();

            if (null != mFragment) 
            {
                Log.d("NAVIGATION_TRACE", "HIDE/DETACH - "+mTag);
                removeDetail(ft);
                ft.hide(mFragment);
                ft.detach(mFragment);
                ft.commitAllowingStateLoss();
            }
        }

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

        public void removeDetail(FragmentTransaction ft) {
            SherlockFragment detailFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag("details");
            if (null != detailFragment && !detailFragment.isDetached()) {
            Log.d("NAVIGATION_TRACE", "DETACH - details");
            ft.detach(detailFragment);
            }
        }
    }   
}

示例片段 - MyPagesFragment :

public class MyPagesFragment extends SherlockListFragment implements
        OnItemClickListener
    {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {
        Log.d("NAVIGATION_TRACE", "MYPAGES - onCreateView");
        View view = inflater.inflate(R.layout.mypages, null);

        // code to set up list adapter here
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("NAVIGATION_TRACE", "MYPAGES - onActivityCreated");
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {
        Log.d("NAVIGATION_TRACE", "MYPAGES - onItemClick");
        ((MainActivity) getActivity()).showDetailView(pages[position].codeId);
    }
}

细节片段

public class DetailFragment extends SherlockFragment implements
        OnItemClickListener
{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {       
        View view = inflater.inflate(R.layout.detail, null);

        // bunch of display / list set up code goes here

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);    
        lvLinks.setOnItemClickListener(this);   
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        // Details page can open other details pages:
        ((MainActivity) getActivity()).showDetailView(pages[position].id);
    }

}

注意:添加的更改是在 Sheldon 的回答之后进行的(令人讨厌的是,他似乎删除了他们的答案和评论),这就是 TabListener 代码在原始部分和后来发布的代码之间发生变化的原因。

我目前已经通过在每个选项卡选择上清空后台堆栈并将顶部选项卡上的返回视为退出应用程序请求来破解解决方案,我想这没关系,但我真的希望用户能够保持如果可能的话,通过选项卡支​​持(因为这样,例如,如果我有五个详细信息页面并且我停下来快速搜索结果证明不存在的东西,我可以回到那些详细信息页面并且仍然上升一个或多个以跟随不同的详细链接。)

4

1 回答 1

1

尝试这个..

    FragmentManager manager = getSupportFragmentManager();
    if (manager.getBackStackEntryCount() > 0)
        getSupportFragmentManager().popBackStack();
    else
        finish();
于 2013-07-25T10:08:42.187 回答