0

Всем привет!

Столкнулся с такой проблемой, используя Navigation Drawer и Fragments. Суть состоит в следующем: после загрузки программы открывается фрагмент "главная страница", и пункт в боковом меню выделяется. Но при выборе другого пункта, пункт "Главной страницы" остается выделенным. Если же мы еще раз нажмем на пункт "Главная страница", то после перехода на другие пункты все корректно. Кто не понял, то можно посмотреть видеодемонстрацию: https://yadi.sk/i/ZUwN52qNuFCdZ

Код MainActivity

public class MainActivity extends AppCompatActivity {

DrawerLayout androidDrawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
boolean doubleBackToExitPressedOnce = false;
private MenuItem prevMenuItem;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    overridePendingTransition(R.anim.anim1, R.anim.anim2);

    initInstancesDrawer();

    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle("System Tweaker PRO");
    }

    Bundle bundle = new Bundle();
    getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.content, HomeFragment.newInstance(bundle))
            .commit();

   ...


}


private void initInstancesDrawer() {

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

    androidDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_design_support_layout);
    actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, androidDrawerLayout, R.string.app_name, R.string.app_name);
    androidDrawerLayout.setDrawerListener(actionBarDrawerToggle);

    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_drawer);
    if (navigationView != null) {
        setupDrawerContent(navigationView);
    }

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

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    actionBarDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onBackPressed() {
    if (this.androidDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        this.androidDrawerLayout.closeDrawer(GravityCompat.START);
    } else {
        if (doubleBackToExitPressedOnce || getSupportFragmentManager().getBackStackEntryCount() != 0) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            System.exit(0);
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, R.string.close, Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }

}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            androidDrawerLayout.openDrawer(GravityCompat.START);
            return true;

    }
    return super.onOptionsItemSelected(item);
}


private void setupDrawerContent(NavigationView navigationView) {
    final Resources res = getResources();
    navigationView.getMenu().getItem(0).setChecked(true);
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    if (prevMenuItem != null)
                        prevMenuItem.setChecked(false);


                    menuItem.setChecked(true);
                    Bundle bundle = new Bundle();
                    String fragmentTitle = null;
                    int id = menuItem.getItemId();
                    switch (menuItem.getItemId()) {
                        case R.id.navigation_drawer_item1:
                            fragmentTitle = "System Tweaker PRO";
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, HomeFragment.newInstance(bundle))
                                    .commit();


                            break;
                        case R.id.navigation_drawer_item2:
                            fragmentTitle = res.getString(R.string.infoabout);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, AboutFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item3:
                            fragmentTitle = res.getString(R.string.speedup);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, OneClickFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item4:
                            fragmentTitle = res.getString(R.string.batterytweaks);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, BatteryTweaksFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item6:
                            fragmentTitle = res.getString(R.string.internettweaks);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, InternetTweaksFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item7:
                            fragmentTitle = res.getString(R.string.systemtweaks);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, SystemTweaksFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item5:
                            fragmentTitle = res.getString(R.string.calbattery);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, BatteryFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item13:
                            fragmentTitle = "FSTRIM";
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, FstrimFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item8:
                            fragmentTitle = res.getString(R.string.mediatweaks);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, MediaTweaksFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item9:
                            fragmentTitle = res.getString(R.string.backupandrestore);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, BackupFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item10:
                            fragmentTitle = res.getString(R.string.soglasenie);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, CautonFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item11:
                            fragmentTitle = res.getString(R.string.connect);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, ConnectWithDeveloperFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item12:
                            fragmentTitle = res.getString(R.string.aboutapp);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, AboutProgramFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item17:
                            fragmentTitle = res.getString(R.string.gpstitle);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, GPSTweaksFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item14:
                            fragmentTitle = "Entropy Generator";
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, EntropyFragment.newInstance(bundle))
                                    .commit();
                            break;

                        case R.id.navigation_drawer_item15:
                            fragmentTitle = res.getString(R.string.varioustweaks);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, VariosTweaksFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item16:
                            fragmentTitle = res.getString(R.string.sovetspowersave);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, SovetsPowerSaveFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item22:
                            fragmentTitle = res.getString(R.string.rebootmanager);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, RebootManagerFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item19:
                            fragmentTitle = res.getString(R.string.sovetsperfomance);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, SovetsPerfomanceFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item20:
                            fragmentTitle = "MediaServer | MediaScanner";
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, MediaServerFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item21:
                            fragmentTitle = "SDCard R/W Fix";
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, SDFixFragment.newInstance(bundle))
                                    .commit();
                            break;
                        case R.id.navigation_drawer_item23:
                            fragmentTitle = res.getString(R.string.dpititle);
                            getSupportFragmentManager()
                                    .beginTransaction()
                                    .setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left)
                                    .replace(R.id.content, DPIChangerFragment.newInstance(bundle))
                                    .commit();
                            break;

                        case R.id.navigation_drawer_item24:
                            fragmentTitle = "System Tweaker PRO";
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                public void run() {
                                    Intent vk = new Intent();
                                    Uri address = Uri.parse("http://vk.com/nowenui_official_group");
                                    Intent openlink = new Intent(Intent.ACTION_VIEW, address);
                                    startActivity(openlink);
                                }
                            }, 300);

                            menuItem.setChecked(false);

                            break;

                        case R.id.navigation_drawer_item25:
                            fragmentTitle = "System Tweaker PRO";
                            Handler handler2 = new Handler();
                            handler2.postDelayed(new Runnable() {
                                public void run() {
                                    Intent twitter = new Intent();
                                    Uri addresstwi = Uri.parse("https://twitter.com/intent/user?user_id=4771768877");
                                    Intent openlinktwi = new Intent(Intent.ACTION_VIEW, addresstwi);
                                    startActivity(openlinktwi);
                                }
                            }, 300);

                            menuItem.setChecked(false);

                            break;

                        case R.id.navigation_drawer_item18:
                            Intent intent = new Intent(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            int pid = android.os.Process.myPid();
                            android.os.Process.killProcess(pid);
                            break;
                    }

                    if (getSupportActionBar() != null) {
                        getSupportActionBar().setTitle(fragmentTitle);
                    }

                    androidDrawerLayout.closeDrawers();
                    prevMenuItem = menuItem;
                    return true;
                }
            });
}

private void copyAssets() {
    AssetManager assetManager = this.getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);
            File outFile = new File(this.getExternalFilesDir(null), filename);
            out = new FileOutputStream(outFile);
            copyFile(in, out);
        } catch (IOException e) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

}

Код res/menu/navigation_drawer_menu_items.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/navigation_drawer_item1"
    android:icon="@drawable/home"
    android:title="@string/glavnays" />
<item
    android:id="@+id/navigation_drawer_item10"
    android:icon="@drawable/warning"
    android:title="@string/soglasenie" />
<item android:title="@string/main">
    <menu>
        <item
            android:id="@+id/navigation_drawer_item2"
            android:icon="@drawable/phone"
            android:title="@string/infoabout" />
        <item
            android:id="@+id/navigation_drawer_item3"
            android:icon="@drawable/oneclick"
            android:title="@string/speedup" />

        <item
            android:id="@+id/navigation_drawer_item5"
            android:icon="@drawable/battery"
            android:title="@string/calbattery" />

        <item
            android:id="@+id/navigation_drawer_item21"
            android:icon="@drawable/sd"
            android:title="SDCard R/W Fix" />

        <item
            android:id="@+id/navigation_drawer_item23"
            android:icon="@drawable/dpi"
            android:title="DPI Changer" />

        <item
            android:id="@+id/navigation_drawer_item9"
            android:icon="@drawable/backup"
            android:title="@string/backupandrestore" />

        <item
            android:id="@+id/navigation_drawer_item22"
            android:icon="@drawable/reboot_command"
            android:title="@string/rebootmanager" />
    </menu>
</item>

<item android:title="@string/tweaks">
    <menu>
        <item
            android:id="@+id/navigation_drawer_item4"
            android:icon="@drawable/tweak_battery"
            android:title="@string/batterytweaks" />
        <item
            android:id="@+id/navigation_drawer_item6"
            android:icon="@drawable/wifi"
            android:title="@string/internettweaks" />
        <item
            android:id="@+id/navigation_drawer_item7"
            android:icon="@drawable/android"
            android:title="@string/systemtweaks" />
        <item
            android:id="@+id/navigation_drawer_item13"
            android:icon="@drawable/fstrim"
            android:title="FSTRIM" />
        <item
            android:id="@+id/navigation_drawer_item14"
            android:icon="@drawable/entropy"
            android:title="Entropy Generator" />
        <item
            android:id="@+id/navigation_drawer_item20"
            android:icon="@drawable/mediascanner"
            android:title="MediaServer | MediaScanner" />
        <item
            android:id="@+id/navigation_drawer_item8"
            android:icon="@drawable/media_tweaks"
            android:title="@string/mediatweaks" />
        <item
            android:id="@+id/navigation_drawer_item17"
            android:icon="@drawable/gps"
            android:title="@string/gpstitle" />

        <item
            android:id="@+id/navigation_drawer_item15"
            android:icon="@drawable/varios"
            android:title="@string/varioustweaks" />
    </menu>
</item>
<item android:title="@string/sovets">
    <menu>
        <item
            android:id="@+id/navigation_drawer_item16"
            android:icon="@drawable/powersave"
            android:title="@string/sovetspowersave" />

        <item
            android:id="@+id/navigation_drawer_item19"
            android:icon="@drawable/memory"
            android:title="@string/sovetsperfomance" />
    </menu>
</item>
<item android:title="@string/prochee">
    <menu>
        <item
            android:id="@+id/navigation_drawer_item11"
            android:icon="@drawable/email"
            android:title="@string/connect" />

        <item
            android:id="@+id/navigation_drawer_item24"
            android:icon="@drawable/vkcircle"
            android:title="Наша группа ВК" />

        <item
            android:id="@+id/navigation_drawer_item25"
            android:icon="@drawable/twittercircle"
            android:title="Наша твиттер" />

        <item
            android:id="@+id/navigation_drawer_item12"
            android:icon="@drawable/info"
            android:title="@string/aboutapp" />
        <item
            android:id="@+id/navigation_drawer_item18"
            android:icon="@drawable/exit"
            android:title="@string/exit" />
    </menu>
</item>

Код res/layout/activity_main.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_design_support_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <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/ThemeOverlay.AppCompat.Light"
                app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

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

        <LinearLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/appbar"
            android:layout_margin="@dimen/activity_horizontal_margin"
            android:orientation="vertical"></LinearLayout>

    </LinearLayout>

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

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_drawer"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/navigation_header"
    app:menu="@menu/navigation_drawer_menu_items" />

4
  • Покажите разметку меню этого элемента
    – Silento
    16 авг 2016 в 7:05
  • разметку меню в студию...
    – Nikotin N
    16 авг 2016 в 7:18
  • @Asgard добавил
    –  NowenUI
    16 авг 2016 в 9:03
  • @NikotinN добавил)
    –  NowenUI
    16 авг 2016 в 10:30

1 ответ 1

1

Решил проблему добавлением следующего кода в initInstancesDrawer()

      navigationView.getMenu().getItem(0).setChecked(true);
      navigationView.getMenu().performIdentifierAction(R.id.navigation_drawer_item1, 0);
1
  • если добавляешь 2-ю строку, то первая не нужна. performIdentifierAction вызывает нажатие на указанный пункт меню, поэтому он должен сам выделиться и загрузить нужный фрагмент.
    – Nikotin N
    16 авг 2016 в 12:29

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.