当我将片段添加到我的视图寻呼机(在嵌套滚动视图中)时,我无法使用设备后退按钮退出应用程序

When I am adding fragment to my view pager (in nested scroll view), I can not exit from application with device back button

这是我的 activity_main 代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:layoutDirection="rtl"
    tools:context=".MainActivity"
    tools:openDrawer="start">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:paddingTop="@dimen/appbar_padding_top"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:layoutDirection="rtl"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:title="@string/app_name">

            </android.support.v7.widget.Toolbar>

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layoutDirection="rtl" />


        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <com.duolingo.open.rtlviewpager.RtlViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layoutDirection="rtl"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:layoutDirection="rtl"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/menu_drawer" />


</android.support.v4.widget.DrawerLayout>

我想在 NestedScrollView 的 ViewPager 中添加一些片段。 如果不向 ViewPager 添加片段,一切正常,我可以通过设备后退按钮退出应用程序,但是当我向 ViewPager 添加片段时,我无法通过按设备后退按钮退出应用程序。(后退按钮正在工作,例如可以关闭软键盘)

这是我的片段代码: (空片段!)

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
    ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_jadvalyab,container,false);
}

这是我的适配器:

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    private ArrayList<Fragment> fragmentsList = new ArrayList<>();
    private ArrayList<String> fragsTitleList = new ArrayList<>();

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

    public void addFragment(Fragment fragment,String title){
        fragmentsList.add(fragment);
        fragsTitleList.add(title);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return fragsTitleList.get(position);
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentsList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentsList.size();
    }
}

有没有人有解决这个问题的想法?

谢谢。

编辑:

通过从 activity_main 中的协调器布局中删除 NestedScrollingView 并将其放入片段布局(在 viewpager 内)来解决问题。 但我仍然不知道为什么设备后退按钮在以前的状态下不起作用。

试试这个

@Override
public void onBackPressed() {
    //Your Action
}

覆盖您的 MainActivity 中的 onBackPress(){} 事件,该事件包含上述 xml 布局。

@Override
public void onBackPressed() {
    finish();
}

覆盖 OnBackPressed() 方法,或者您可以这样编写适配器。

 public class Adapter extends FragmentStatePagerAdapter {
public Adapter (FragmentManager fm) {
    super(fm);
}
 // you can add fragments according to your requirement
@Override
public Fragment getItem(int position) {
    Fragment fragment= null;
    switch (position){
        case 0:
            fragment= new fragmentDay();
            break;
        case 1:
            fragment= new fragmentWeek();
            break;
        case 2:
            fragment= new fragmentMonth();
            break;

    }
    return fragment;
}

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

}

并在 activity 内部将片段管理器传递给适配器构造函数。

    fragmentManager= getSupportFragmentManager();
    adapter= new Adapter(fragmentManager);
    viewPager.setAdapter(adapter);

我在 viewpager 中使用了 tablayout

tabLayout.setupWithViewPager(viewPager);
    tabLayout.setTabsFromPagerAdapter(adapter);
    tabLayout.getTabAt(0).setText("Day");
    tabLayout.getTabAt(1).setText("Week");
    tabLayout.getTabAt(2).setText("Month");
    tabLayout.getTabAt(1).select(); 
    tabLayout.setSelectedTabIndicatorColor(Color.WHITE);

我认为问题的发生是因为您为 ViewPager 使用了第三方库。 只需将以下代码复制并粘贴到 "activity_main.xml" 文件的位置即可。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main2" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/menu_drawer" />

</android.support.v4.widget.DrawerLayout>

我已经像这样将片段初始化为 ViewPager

ViewPager viewPager2 = findViewById(R.id.viewpager);
    MyFragmentPagerAdapter pagerAdapter2 = new MyFragmentPagerAdapter(getSupportFragmentManager());
    pagerAdapter2.addFragment(TestFragment.createInstance(),"Home");
    viewPager2.setAdapter(pagerAdapter2);
    TabLayout tabLayout2 = findViewById(R.id.tabs);
    tabLayout2.setupWithViewPager(viewPager2);

这里是Testfragment.javaclass

public class TestFragment extends Fragment {

public static TestFragment createInstance() {
    TestFragment profileFragment = new TestFragment();
    return profileFragment;
}

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

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}
}

"Main2Activity.java" class 的完整代码在这里

public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    initViewPager();
}

private void initViewPager() {
    ViewPager viewPager2 = findViewById(R.id.viewpager);
    MyFragmentPagerAdapter pagerAdapter2 = new MyFragmentPagerAdapter(getSupportFragmentManager());
    pagerAdapter2.addFragment(TestFragment.createInstance(),"Home");
    viewPager2.setAdapter(pagerAdapter2);
    TabLayout tabLayout2 = findViewById(R.id.tabs);
    tabLayout2.setupWithViewPager(viewPager2);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

编辑:

代码"content_main2.xml"

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.v4.widget.NestedScrollView>

"fragment_jadvalyab.xml" 的代码在

之后
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Best Wishes"
android:gravity="center"/>
</LinearLayout>