android-fragments 如何在打开某个片段时隐藏导航抽屉?

iyr7buue  于 2022-11-14  发布在  Android
关注(0)|答案(3)|浏览(193)

我是一个很新的android开发。我想隐藏导航抽屉时,用户没有登录。所以基本上,它会显示登录片段(更好地在全屏像Facebook android)。如果用户已经登录,导航抽屉将始终显示。
MainActivity.java

public class MainActivity extends AppCompatActivity {

private DrawerLayout navDrawerLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle navDrawerToggle;

private SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Find our drawer view
    NavigationView navDrawerView = (NavigationView) findViewById(R.id.navdrawer_view);
    // Setup drawer view
    setupDrawerContent(navDrawerView);

    navDrawerToggle = setupDrawerToggle();

    pref = getPreferences(0);
    initFirstFrame();
}

private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, navDrawerLayout, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

private void setupDrawerContent(NavigationView navDrawerView) {
    navDrawerView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);
                    return true;
                }

            });
}

public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked
    Fragment fragment = null;
    Class fragmentClass;
    switch(menuItem.getItemId()) {
        case R.id.events:
            fragmentClass = EventsFragment.class;
            break;
        case R.id.pengumuman:
            fragmentClass = NewsFragment.class;
            break;
        case R.id.edit_profil:
            fragmentClass = ProfileFragment.class;
            break;
        default:
            fragmentClass = EventsFragment.class;
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.frame_content, fragment).commit();

    // Highlight the selected item has been done by NavigationView
    menuItem.setChecked(true);
    // Set action bar title
    setTitle(menuItem.getTitle());
    // Close the navigation drawer
    navDrawerLayout.closeDrawers();
}

private void initFirstFrame(){
    Fragment fragment;
    if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
        fragment = new ProfileFragment();
    }else {
        fragment = new LoginFragment();
        // in this login fragment, navdrawer should be invisible, the toolbar too I guess
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_content,fragment);
    fragmentTransaction.commit();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return navDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

// 'onPostCreate' called when activity start-up is complete after 'onStart()'
// NOTE! Make sure to override the method with only a single 'Bundle' argument
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred
    navDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    navDrawerToggle.onConfigurationChanged(newConfig);
}

}
tpxzln5u

tpxzln5u1#

定义一个接口,例如DrawerLocker:

interface DrawerLocker{
   public void setDrawerLocked(boolean shouldLock);
}

在包含NavigationDrawer的Activity中实现此接口并重写此方法。

class YourActivity implements DrawerLocker{
...
...
public void setDrawerLocked(boolean enabled){
    if(enabled){
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }else{
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

}

现在,在Fragment的onCreateView中,调用此方法,如下所示:

((DrawerLocker)getActivity()).setDrawerLocked(true);

在Fragment的onDestroyView中,重新启用抽屉式布局:

((DrawerLocker)getActivity()).setDrawerLocked(false);
m4pnthwp

m4pnthwp2#

当堆栈中有多个片段时,活动onCreate方法中的这段代码将阻塞drawer:

getSupportFragmentManager().addOnBackStackChangedListener(() -> {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        } else {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }
    });
3df52oht

3df52oht3#

这是您所需要的全部,如果您不希望抽屉处于某个状态,请检查您的目的地

单一活动架构,将以下代码放在活动onCreate中

private fun changeDrawerState() {
    val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
    navHostFragment.navController.addOnDestinationChangedListener(listener = { _, destination, _ ->
        //set in case app asked for verify auth, signIn page drawer will be locked
        if (destination.id== R.id.signInFragment) {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        } else if (drawer.getDrawerLockMode(GravityCompat.START) != DrawerLayout.LOCK_MODE_UNLOCKED) {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
        }
    })
}

根据抽屉打开方向启动重力补偿

相关问题