Tabbed-FragmentActivity中的OnBackPressed不起作用

时间:2017-02-20 08:36:57

标签: android android-fragments

我在带有视图寻呼机和导航抽屉的选项卡中显示多个片段。 我定义了一个控制所有片段的TabFragment 我想展示退出对话并完成应用程序 但是当我按下Back Button时显示空白屏幕 我甚至评论了onbackpressed方法,但是当我按下后退按钮时它仍显示空白屏幕 我试过这个:Android onBackPressed() not working但不能。

主要活动

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;
    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
        View headerView = LayoutInflater.from(this).inflate(R.layout.drawer_header, null);
        mNavigationView.addHeaderView(headerView);
        mNavigationView.getHeaderView(0).setVisibility(View.GONE);

        int width = getResources().getDisplayMetrics().widthPixels / 2;
        DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mNavigationView.getLayoutParams();
        params.width = width;

        mNavigationView.setLayoutParams(params);
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                menuItem.setChecked(true);
                mDrawerLayout.closeDrawers();
                if (menuItem.getItemId() == R.id.Top) {
                    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
                }
                if (menuItem.getItemId() == R.id.Latest) {
                    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.frame_container, new Fragment1()).commit();
                }
                return false;
            }
        });

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
    }

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

    public void ExitDialogue() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.app_name);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setMessage("Do you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

Tab Fragment实际上会在带有视图寻呼机的选项卡中加载2个片段。

标签片段

public class TabFragment extends Fragment {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private static int int_items = 2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_layout, container, false);
        tabLayout = (TabLayout) v.findViewById(R.id.tabs);
        viewPager = (ViewPager) v.findViewById(R.id.viewpager);
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        viewPager.setOffscreenPageLimit(int_items - 1);
        viewPager.setPageTransformer(true, new DepthPageTransformer());
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        return v;
    }

    class MyAdapter extends FragmentPagerAdapter {
        MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new Fragment1();
                case 1:
                    return new Fragment2();
            }
            return null;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return getResources().getString(R.string.tab1);
                case 1:
                    return getResources().getString(R.string.tab2);
            }
            return null;
        }
    }
}

5 个答案:

答案 0 :(得分:1)

**CREATE YOUR MAINACTIVITY SUCH AS:**

public class MainActivity extends AppCompatActivity {

 public ViewPager viewPager;
 private ArrayList<Fragment> allPagerData;
   private MainactivityPagerAdapter mainAdapter;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.addTab(tabLayout.newTab().setText("Fragment1"));
        tabLayout.addTab(tabLayout.newTab().setText("Fragment1"));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        final PagerAdapter adapter = new PagerAdapter
                (this.getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                Log.e("onTabReselected: ",":"+tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                Log.e("onTabReselected: ",":"+tab);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                Log.e("onTabReselected: ",":"+tab);
            }
        });

        initViews();
    }

    public void initViews(){

        createPager();

        mainAdapter = new MainactivityPagerAdapter(this.getSupportFragmentManager(), allPagerData);
        viewPage.setAdapter(mainAdapter);
        viewPager.setCurrentItem(0);


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {


                if (position == allPagerData.size() - 1) {
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void createPager() {
        allPagerData = new ArrayList<>();

        Fragment1 fragment1 = new Fragment1();
        allPagerData.add(fragment1);

         Fragment2 fragment2 = new Fragment2();
        allPagerData.add(fragment2);


    }

        @Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() != 0) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        }else {
            super.onBackPressed();      
            // do whatever want to do if you want finished activity you can
        }
    }
}

=============================================== ===============

Your MainactivityPagerAdapter 


public class MainactivityPagerAdapter extends FragmentPagerAdapter {

    private final ArrayList<Fragment> allFragments;

    public MainactivityPagerAdapter(FragmentManager fm, ArrayList<Fragment> allFragments) {
        super(fm);
        this.allFragments = allFragments;
    }

    /**
     * Return the Fragment associated with a specified position.
     *
     * @param position
     */
    @Override
    public Fragment getItem(int position) {
        return allFragments.get(position);
    }

    /**
     * Return the number of views available.
     */
    @Override
    public int getCount() {

        return (allFragments != null) ? allFragments.size() : 0;
    }
}

=============================================== ========================== 你的PagerAdapter

public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                Fragment1 tab1 = new Fragment1();
                return tab1;
            case 1:
                Fragment2 tab2 = new Fragment2();
                return tab2;


            default:
                return null;
        }
    }

    @Override
    public int getItemPosition(Object object) {

        return super.getItemPosition(object);
    }

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

答案 1 :(得分:0)

从onBackPressed()中删除destinationController并尝试。

答案 2 :(得分:0)

<强>问题

  

当我按下Back Button时显示空白屏幕。

试试这个。

undefined

答案 3 :(得分:0)

让你的MainActivity是一个处理你的Tabfragment的父Activity,问题是你的父片段无法处理你的子tabfragment,所以onbackpress在这里不起作用。

答案 4 :(得分:0)

由于您尚未发布日志,因此您可以查看这些内容。

  • 尝试使用onBackPress()方法中的断点进行检查。以检查控件是否到位。
  • 如前所述,在onCreate方法上绑定mDrawerLayout并将其设为公共变量。
  • 检查Fragment和FragmentManager是否是对v4.Fragment和v4.FragmentManager的引用(必须相同)