我的主要活动是一个带有选项卡的滑动视图,它可以直接用于切换到特定的片段。我基本上是跟着开发人员指南做的。到目前为止,这是很好的和预期的。
但是,我现在在菜单中有几个项(设置,约),它们不应该显示为ViewPager的一部分,而是应该完全替换ViewPager,并在操作栏中设置“导航向上”功能。按照这个问题的答案,我知道如何使用BackStack操作栏,并显示“导航向上”提供的功能。
然而,我不确定替换ViewPager的最佳方式是什么。据我所知,我可以尝试禁用所有ViewPager功能并使其看起来像一个片段(例如禁用选项卡和滑动),或者我可以使用嵌套片段。然而,我不相信这两种选择都是“干净的”。
也许我忽略了一些东西,并且有一种更直观的方法来实现同样的目标?你们对此有什么想法?你们是如何实现“基本”的呢?
P.S.:很明显,我可以用活动来做这个,但是我认为一个活动太重了,不适合简单的“关于”文本,在我看来,现在只要有可能,就应该尝试使用片段。
发布于 2014-05-02 10:42:06
正如我所理解的,您可以将ViewPager
作为FrameLayout
和add()
--FrameLayout
和add()
--将addToBackState()
方法中的"about“片段放在ViewPager之上。
您将避免禁用或刷新ViewPager。只需在上面添加一个新片段。
更新
我可以使用add()
方法和添加的片段上的自定义background
来实现这一点,以避免重叠问题。最后,将此背景设置为clickable
,以防止后台ViewPager的单击事件。
请参阅我的活动布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.viewpageroverlap.MainActivity"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
我的菜单项事件:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, OverlapFragment.newInstance(990), null).addToBackStack(null).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
我的重叠片段布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.viewpageroverlap.MainActivity$OverlapFragment"
android:background="#FF0000"
android:clickable="true" >
<TextView
android:id="@+id/section_label"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
</RelativeLayout>
这给了我这个输出:
注意:我使用了红色背景,但您可以尝试使用Android,避免使用文件中声明为android:background="@android:color/white"
__的颜色。
带制表符的
您可以执行与上面相同的操作,并使用NAVIGATION_MODE_STANDARD
重置导航:
if (id == R.id.action_settings) {
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, OverlapFragment.newInstance(990), null).addToBackStack(null).commit();
return true;
}
然后,当用户返回到ViewPager (当他按home按钮或硬件后退按钮)时,将旧导航重置为:
// do the same with android.R.id.home inside onOptionsItemSelected
@Override
public void onBackPressed() {
// check if the "about" fragment is still displayed
if(this.getSupportFragmentManager().getBackStackEntryCount() > 0) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
this.getSupportFragmentManager().popBackStack();
}
}
发布于 2014-05-02 10:41:43
只需将ViewPager放在自己的片段中,并在希望使用常规片段事务更改为另一个片段时将其替换。
如果您打开addToBackStack,这些事务将以自然的方式对back按钮作出反应。
https://stackoverflow.com/questions/23434698
复制相似问题