[英]Replace ViewPager by another fragment
我的主要活动是在操作栏中带有选项卡的“滑动视图”,可用于直接更改为特定片段。 我基本上遵循了开发人员指南 。 到目前为止,这工作正常且符合预期。
但是,我现在在菜单中有几个项目(“设置”,“关于”),这些项目不应显示为ViewPager的一部分,而应完全替换ViewPager并在操作栏中设置“向上导航”功能。 在回答这个问题的答案之后,我知道如何使用BackStack来操纵操作栏并显示“导航”能力。
但是我不确定替换ViewPager的最佳方法是什么。 据我所知,我可以尝试禁用所有ViewPager功能并使它显示为单个片段(例如,禁用选项卡和滑动),或者可以使用嵌套片段。 但是,我不认为这两个选项都是“干净的”。
也许我在这里忽略了某些东西,并且有一种更直观的方法来实现这一点? 你们在想什么,您如何实现这种“基本”的东西?
PS:显然我可以为此使用活动,但是我认为一个活动对于简单的“关于”文本来说太繁琐了,据我所知,这几天应该尽可能使用Fragments。
据我了解,您可以将ViewPager
作为FrameLayout
放置在父对象中,并使用addToBackState()
上方的addToBackState addToBackState()
方法add()
“ about”片段。
您将避免禁用或刷新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 Resources Color,并避免使用文件中声明为android:background="@android:color/white"
。
带标签
您可以执行上述操作,并使用NAVIGATION_MODE_STANDARD
重置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时(当他按下主屏幕按钮或硬件后退按钮时),将旧导航重置为:
// 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();
}
}
只需将ViewPager放在其自己的片段中,并在要使用常规片段事务更改为另一个片段时将其替换。
如果打开addToBackStack,则这些事务将以自然的方式对后退按钮做出反应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.