web-dev-qa-db-ja.com

既存のコードにナビゲーションドロワーを追加するにはどうすればよいですか?

ナビゲーションドロワーを適用したいメニューボタン付きのナビゲーションパネルがあるアプリがあります。現在は画面全体を占めていますが、ナビゲーションドロワーを適用して画面の3/4に制限したいと思います。 、しかし私はこれまでナビゲーションドロワーに触れたことがないので、手がかりがないので、ヘルプやガイダンスは素晴らしいでしょう。また、いくつかのドキュメントを調べて混乱しました:(これが私のコードです:

ナビゲーションパネルのレイアウトクラスは次のとおりです。

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:foo="http://schemas.Android.com/apk/res/com.justin.a"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:background="@drawable/bg_texture"
    Android:clickable="true" >

<RelativeLayout 
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:layout_marginLeft="@dimen/nav_margin"
    Android:layout_marginTop="@dimen/nav_margin"
    Android:layout_marginRight="@dimen/nav_margin"
    Android:layout_marginBottom="@dimen/nav_margin"
    Android:background="#242424"
    >

    <ScrollView
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:paddingLeft="@dimen/nav_padding"
        Android:paddingTop="@dimen/nav_padding"
        Android:paddingRight="@dimen/nav_padding"

        >

        <LinearLayout
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:divider="@Android:drawable/divider_horizontal_bright"
            Android:orientation="vertical"
            Android:showDividers="middle"

             >


             <com.justin.a.utils.FontTextView
                Android:id="@+id/nav_option_dashboard"
                style="@style/a.TextView.NavigationItem"
                Android:layout_width="match_parent"
                Android:layout_height="@dimen/button_ht"
                Android:layout_marginBottom="1px"
                Android:onClick="onDashboardClicked"
                Android:text="@string/nav_option_dashboard"
                Android:textSize="@dimen/navigation_panel_text"
                foo:customFont="cabin.medium.ttf"
                Android:padding="@dimen/nav_option_padding"
                Android:background="@drawable/nav_background_button"
                    />  
            <com.justin.a.utils.FontTextView
                Android:id="@+id/nav_option_news"
                style="@style/a.TextView.NavigationItem"
                Android:layout_width="match_parent"
                Android:layout_height="@dimen/button_ht"
                foo:customFont="cabin.medium.ttf"
                Android:textSize="@dimen/navigation_panel_text"
                Android:layout_marginBottom="1px"
                Android:onClick="onNewsClicked"
                Android:text="@string/nav_option_news"
                Android:padding="@dimen/nav_option_padding"
                Android:background="@drawable/nav_background_button"

                 />

            <com.justin.a.utils.FontTextView
                Android:id="@+id/nav_option_markets"
                style="@style/a.TextView.NavigationItem"
                Android:layout_width="match_parent"
                Android:layout_height="@dimen/button_ht"
                Android:textSize="@dimen/navigation_panel_text"
                Android:layout_marginBottom="1px"
                Android:onClick="onMarketClicked"
                Android:text="@string/nav_option_markets" 
                foo:customFont="cabin.medium.ttf"
                Android:padding="@dimen/nav_option_padding"
                Android:background="@drawable/nav_background_button"

                />

            <com.justin.a.utils.FontTextView
                Android:id="@+id/nav_option_lists"
                style="@style/a.TextView.NavigationItem"
                Android:layout_width="match_parent"
                Android:layout_height="@dimen/button_ht"
                Android:textSize="@dimen/navigation_panel_text"
                Android:layout_marginBottom="1px"
                Android:text="@string/nav_option_lists"
                foo:customFont="cabin.medium.ttf"
                Android:onClick="onListsClicked"
                Android:padding="@dimen/nav_option_padding"
                Android:background="@drawable/nav_background_button"

               />

            <!--  UncommentForAlerts- Remove Android:visibility="gone" -->
            <com.justin.a.utils.FontTextView
                Android:id="@+id/nav_option_alerts"
                style="@style/a.TextView.NavigationItem"
                Android:layout_width="match_parent"
                Android:layout_height="@dimen/button_ht"
                Android:textSize="@dimen/navigation_panel_text"
                Android:layout_marginBottom="1px"
                foo:customFont="cabin.medium.ttf"
                Android:padding="@dimen/nav_option_padding"
                Android:onClick="onAlertsClicked"
                Android:text="@string/nav_option_alerts" 
                Android:background="@drawable/nav_background_button"
                Android:visibility="gone"

                />

            <com.justin.a.utils.FontTextView
                Android:id="@+id/nav_option_briefcase"
                style="@style/a.TextView.NavigationItem"
                Android:layout_width="match_parent"
                Android:layout_height="@dimen/button_ht"
                Android:textSize="@dimen/navigation_panel_text"
                Android:layout_marginBottom="1px"
                foo:customFont="cabin.medium.ttf"
                Android:padding="@dimen/nav_option_padding"
                Android:onClick="onBriefcaseClicked"
                Android:text="@string/nav_option_briefcase" 
                Android:background="@drawable/nav_background_button"


                />

        </LinearLayout>
    </ScrollView>

    <ImageButton
        Android:id="@+id/button_information"
        Android:layout_width="@dimen/nav_button"
        Android:layout_height="wrap_content"
        Android:layout_alignParentBottom="true"
        Android:layout_marginBottom="@dimen/nav_padding"
        Android:layout_centerHorizontal="true"
        />

    <ImageButton
        Android:id="@+id/button_settings"
        Android:layout_width="@dimen/nav_button"
        Android:layout_height="wrap_content"
        Android:layout_alignParentBottom="true"
        Android:layout_marginBottom="@dimen/nav_padding"
        Android:layout_toLeftOf="@+id/button_information" />

    <ImageButton
        Android:id="@+id/button_logout"
        Android:layout_width="@dimen/nav_button"
        Android:layout_height="wrap_content"
        Android:layout_alignParentBottom="true"
        Android:layout_marginBottom="@dimen/nav_padding"
        Android:layout_toRightOf="@+id/button_information"
          />

</RelativeLayout>
</RelativeLayout>

これも私のnavigationpanelfragment.Java:-UPDATE ----

public class NavigationPanelFragment extends Fragment implements OnClickListener {

    public static final String TAG_NAVIGATION_PANEL_FRAGMENT = "NavigationPanelFragment";
    public static final String ACTIVE_MENU_ITEM = "ActiveMenuItem";
    private ActionBarDrawerToggle drawerToggle;
    private Fragment lvDrawer;
    public static void newInstance(final FragmentManager manager, final String activeFragmentTag) {
        final NavigationPanelFragment fragment = new NavigationPanelFragment();
        final Bundle arguments = new Bundle();
        arguments.putString(NavigationPanelFragment.ACTIVE_MENU_ITEM, activeFragmentTag);
        fragment.setArguments(arguments);

        final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD);
        fragmentInfo.setAnimation(R.anim.slide_in_from_left, FragmentInfo.NO_ANIMATION);
        fragmentInfo.setPopAnimation(0, R.anim.slide_out_to_left);
        fragmentInfo.setFragmentTag(TAG_NAVIGATION_PANEL_FRAGMENT);
        fragmentInfo.doNotAddToBackStack();
        fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_applications));
        FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
    }

    public static void removeInstance(final FragmentManager manager) {

        Fragment fragment = manager.findFragmentByTag(TAG_NAVIGATION_PANEL_FRAGMENT);
        if (fragment == null) {
            return;
        }

        manager.beginTransaction().setCustomAnimations(0, R.anim.slide_out_to_left).remove(fragment).commitAllowingStateLoss();
    }

    private LogoutListener mLogoutListener = new LogoutListener() {
        @Override
        public void onLogoutOperationFired() {
            final Activity activity = getActivity();
            if(activity != null){
                LoginActivity.newInstance(activity);
                UserProfileManager.clearUserProfileManager();
                FragmentStackManager.getInstance().clearBackStack(getFragmentManager());
                activity.finish();
            }
        }
    };

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        final View view = inflater.inflate(R.layout.fragment_navigation_panel, container, false);
        return view;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onActivityCreated(final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        final ImageButton logoutButton = (ImageButton) getView().findViewById(R.id.button_logout);
        logoutButton.setOnClickListener(this);
        logoutButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_signout_nav_panel));

        final ImageButton infoButton = (ImageButton) getView().findViewById(R.id.button_information);
        infoButton.setOnClickListener(this);
        infoButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_info_nav_panel));

        final ImageButton settingsButton = (ImageButton) getView().findViewById(R.id.button_settings);
        settingsButton.setOnClickListener(this);
        settingsButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_prefs_nav_panel));

        highlightActiveMenuItem();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLogoutListener = null;
    }

    @Override
    public void onResume() {
        MenuUtils.disableSearchMenu(getActivity());
        MenuUtils.disableAlertMenu(getActivity());
        super.onResume();
    }

    @Override
    public void onPause() {
        MenuUtils.enableSearchMenu(getActivity());
        MenuUtils.enableAlertMenu(getActivity());
        super.onPause();
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.button_logout:

                final DialogFragment dialog = new LogoutCancelSignoutDialogFragment(mLogoutListener);
                dialog.show(getActivity().getSupportFragmentManager(), AbsBaseaActivity.TAG_LOGOUT_DIALOG);
\               break;
            case R.id.button_information:
                leaveMainActivity();
                InformationActivity.newInstance(getActivity());
\               break;
            case R.id.button_settings:
                leaveMainActivity();
                PreferencesActivity.newInstance(getActivity());
\               break;
        }
    }
    public ActionBarDrawerToggle getDrawerToggle() {
        return drawerToggle;
    }

    private void leaveMainActivity() {
        removeInstance(getActivity().getSupportFragmentManager());
        final MainActivity activity = (MainActivity) getActivity();
        activity.setNavigationOpen(false);
    }

    private void highlightActiveMenuItem() {
        TextView highlightedTextView = null;
        final String activeFragmentTitle = "";//getArguments().getString(ACTIVE_MENU_ITEM);
        final Resources resources = Application.getAppResources();

        if (resources.getString(R.string.nav_option_news).equals(activeFragmentTitle)) {
            highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_news);

        } else if (resources.getString(R.string.nav_option_markets).equals(activeFragmentTitle)) {
            highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_markets);

        } else if (resources.getString(R.string.nav_option_lists).equals(activeFragmentTitle)) {
            highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_lists);
        } else if (resources.getString(R.string.nav_option_alerts).equals(activeFragmentTitle)) {
            highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_alerts);
        }
        else if (resources.getString(R.string.nav_option_briefcase).equals(activeFragmentTitle)) {
            highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_briefcase);
        } else {
            highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_dashboard);
        }

        highlightedTextView.setTextColor(getResources().getColor(R.color.dark_orange));

    }

}

これが私のacitvity_main.xmlです(動作し、スワイプで空白のパネルが表示されます)

<?xml version="1.0" encoding="utf-8"?>


  <!-- <include layout="@layout/main_title"/> -->

  <!-- <Button Android:text="Main" Android:layout_height="wrap_content"
    Android:id="@+id/btn_refreshbtn_refresh" Android:layout_width="wrap_content">

  </Button> -->
  <Android.support.v4.widget.DrawerLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:id="@+id/drawer_layout"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context=".MainActivity" >

   <FrameLayout 
    Android:id="@+id/fragment_container"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:background="@color/altercolor2">
    </FrameLayout>

    <fragment
        Android:id="@+id/drawer"
        Android:layout_width="240dp"
        Android:layout_height="match_parent"
        Android:layout_gravity="start"
        Android:divider="#666"
        Android:dividerHeight="1dp"
        Android:background="#333"
        Android:paddingLeft="15sp"
        Android:paddingRight="15sp"
        Android:name="com.justin.jar.fragments.NavigationPanelFragment"/>

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

- - 更新しました - -

これも私のmainactivity.Java(ナビゲーションドロワーの下に追加する必要のあるナビゲーションパネル参照があります):

public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
    public static final int REQUEST_CODE_LIST = 100;
    private boolean mIsNavigationOpen = false;
    private DrawerLayout drawerLayout;
    private NavigationPanelFragment dlDrawer;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private boolean mIsSearchBarActive;
     private CharSequence mDrawerTitle;
        private CharSequence mTitle;
    public boolean isNavigationOpen() {
        return mIsNavigationOpen;

    }

    @SuppressWarnings("deprecation")
    public void setNavigationOpen(final boolean isNavigationOpen) {
        this.mIsNavigationOpen = isNavigationOpen;
        final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
        if(isNavigationOpen) {
            mainButton.setBackgroundResource(R.drawable.bg_helios_active);
        } else {
            mainButton.setBackgroundDrawable(null);
        }
    }


    public static void newInstance(final Activity activity) {
        final Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
// 2. App Icon 
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        // 2.1 create ActionBarDrawerToggle

                 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
                            R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close);


                // 2.2 Set actionBarDrawerToggle as the DrawerListener
                drawerLayout.setDrawerListener(actionBarDrawerToggle);

        initiateMainActionBar();

        final FragmentManager supportFragmentManager = getSupportFragmentManager();
        supportFragmentManager.addOnBackStackChangedListener(this);


        if (savedInstanceState == null) {
            mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);

        } else {
            //resetToDashboard(supportFragmentManager);
        }
        //setup drawer

        /* Set up the drawer toggle */
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle("");
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(R.string.app_name);
            }
        };

        // Set the drawer toggle as the DrawerListener
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (dlDrawer.getDrawerToggle().onOptionsItemSelected((Android.view.MenuItem) item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
         actionBarDrawerToggle.syncState();
    }

    private void setupOnClickListenerForMainButton() {
        final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
        mainButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {
                toggleNavigationPanel();
            }
        });
    }

    @Override
    public void manageActionBar() {
        setTitle(null);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
    }

    @Override
    public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
        switch (item.getItemId()) {
            case Android.R.id.home:
                toggleNavigationPanel();
                break;

            default:
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    protected void onResume() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastActions.USER_PROFILE);
        filter.addAction(BroadcastActions.NEWS_IMAGE);
        filter.addAction(BroadcastActions.NEWS_HEADLINES);

        registerReceiver(mMainActivityReceiver, filter);
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(mMainActivityReceiver);
        super.onPause();
        BangoAgent.onIdle();
    }

    public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
        NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
    }

    public void onDashboardClicked(final View view) {
        toggleNavigationPanel();

        if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
            return;
        }

        final FragmentManager manager = getSupportFragmentManager();
        final FragmentTransaction transaction = manager.beginTransaction();
        transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = DashboardFragment.getInstance();
        transaction.hide(mActiveFragment);
        transaction.show(mActiveFragment);
        transaction.commitAllowingStateLoss();
        updateActionBarTitle();
    }

    public void onNewsClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onMarketClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onListsClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onBriefcaseClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onAlertsClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();

    }

    private void toggleNavigationPanel() {
        final FragmentStackManager manager = FragmentStackManager.getInstance();
        if (mIsNavigationOpen) {
            NavigationPanelFragment.removeInstance(getSupportFragmentManager());
            updateActionBarTitle();
            BangoHelper.eventMainNav();
        } else {
            final TextView title = (TextView) findViewById(R.id.main_title);
            title.setText(getString(R.string.title_applications));
            NavigationPanelFragment.newInstance(getSupportFragmentManager(), manager.getTopTitle());
        }


        setNavigationOpen(!mIsNavigationOpen);
    }

    public void updateActionBarTitle() {
        final String title = FragmentStackManager.getInstance().getTopTitle();
        final TextView titleView = (TextView) findViewById(R.id.main_title);
        titleView.setText(title);
    }

    private boolean isFragmentVisible(final String tag) {
        Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
        return fragment != null && tag.equals(fragment.getTag());
    }

    public interface BackPressListener<T extends Fragment> {
        public boolean backPressed(MainActivity fragmentActivity);
    }

    private BackPressListener<Fragment> backPressListener = null;
    public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
            this.backPressListener = backPressListener;
    }


    @Override
    public void onBackPressed() {
        if (backPressListener != null) {
            boolean b = false;
            // Making sure we trigger the backPressed event if the listener is the top fragment
            String bplTag = ((Fragment)backPressListener).getTag();
            Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
            String topFragemtnTag = "";
            if (topFragment != null) {
                topFragemtnTag = topFragment.getTag();
    }

        if (mIsSearchBarActive) {
            MenuUtils.hideSearchView(this);
            mIsSearchBarActive = false;
        } else if (mIsNavigationOpen) {
            toggleNavigationPanel();
        } else if (!FragmentStackManager.getInstance().popTopFragment()) {
            Intent setIntent = new Intent(Intent.ACTION_MAIN);
            setIntent.addCategory(Intent.CATEGORY_HOME);
            setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(setIntent);
        } else {
            Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
            if (topFragment == null) {
                mActiveFragment = DashboardFragment.getInstance();
                ((DashboardFragment)mActiveFragment).refreshDashboard();
            } else if (topFragment instanceof AbsArticlePagerFragment) {
                ((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
            } else if (topFragment instanceof AbsBaseArticleFragment) {
                ((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
            }
        }

        updateActionBarTitle();
    }


    public void setActiveFragment(final Fragment fragment) {
        mActiveFragment = fragment;
    }

    public void setIsSearchBarActive(final boolean isSearchBarActive){
        mIsSearchBarActive = isSearchBarActive;
    }

    @Override
    public void onBackStackChanged() {
        for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
            final BackStackEntry bse = getSupportFragmentManager().getBackStackEntryAt(i);
            Log.d("BackStack", "Changed: " + bse.getName());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LIST) {
            if (resultCode == RESULT_OK) {
                Fragment fragment = FragmentStackManager.getInstance().getTopFragment();

                if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
                    DashboardFragment.getInstance().onUpdate();
                } else if (fragment instanceof ListsContainerFragment) {
                    ((ListsContainerFragment) fragment).onUpdate();
                } else if (fragment instanceof ListDetailsFragment) {
                    ((ListDetailsFragment) fragment).onUpdate(data);
                }
            }
        }
    }

    @Override
    public void refreshScreen() {
        Fragment fragment = FragmentStackManager.getInstance().getTopFragment();

        if (fragment == null) { // Implies DashboardFragment
            DashboardFragment.getInstance().refreshScreen();
        } else if (fragment instanceof ListsContainerFragment) {
            ((ListsContainerFragment) fragment).refreshScreen();
        } else if (fragment instanceof ListDetailsFragment) {
            ((ListDetailsFragment) fragment).refreshScreen();
        } else if (fragment instanceof MarketsFragment) {
            ((MarketsFragment) fragment).refreshScreen();
        }else if (fragment instanceof AlertsContainerFragment) {
            ((AlertsContainerFragment) fragment).refreshScreen();
        }

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

    }
}
9

これは、ナビゲーションドロワーを追加するために従うべき良い記事です: http://developer.Android.com/training/implementing-navigation/nav-drawer.html

Activity_main.xmlのドロワービューはListView(データを設定していない)であるため、ナビゲーションドロワーに空白のパネルが表示されています。

このビューをフラグメントにします。

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:tools="http://schemas.Android.com/tools"
    Android:id="@+id/drawer_layout"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <!-- This fragment container is your the place to put your activities content -->

    <FrameLayout
        Android:id="@+id/fragment_container"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:background="@color/altercolor2" />

    <!--
    This is your navigation drawer. You can adjust the width here, but it should
    be between 240dp and 320dp
    -->

    <fragment
        Android:id="@+id/drawer"
        Android:layout_width="240dp"
        Android:layout_height="match_parent"
        Android:layout_gravity="start"
        class="com.yourapp.NavigationPanelFragment" />

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

MainActivityは次のようになります。

public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
    public static final int REQUEST_CODE_LIST = 100;

    private Fragment mDrawer;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;

    public boolean isNavigationOpen() {
        return mDrawerLayout.isDrawerOpen(mDrawer);
    }

    @SuppressWarnings("deprecation")
    public void setNavigationOpen(final boolean isNavigationOpen) {
        final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
        if(isNavigationOpen) {
            mainButton.setBackgroundResource(R.drawable.bg_helios_active);
        } else {
            mainButton.setBackgroundDrawable(null);
        }
    }




    public static void newInstance(final Activity activity) {
        final Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

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

        initiateMainActionBar();

        final FragmentManager supportFragmentManager = getSupportFragmentManager();
        supportFragmentManager.addOnBackStackChangedListener(this);


        if (savedInstanceState == null) {
            mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
            BangoHelper.onStartSession(this);

        } else {
            resetToDashboard(supportFragmentManager);
        }

        //setup drawer


        //this is our drawer layout that contains the navigation drawer and your content
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        //this is the navigation drawer fragment
        mDrawer = (NavigationPanelFragment) findViewById(R.id.drawer);
    }

    private void resetToDashboard(final FragmentManager supportFragmentManager) {
        FragmentStackManager.getInstance().clearBackStack(supportFragmentManager);
        mActiveFragment = DashboardFragment.getInstanceWithNoTransition(supportFragmentManager);
    }

    private void initiateMainActionBar() {
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(R.layout.actionbar_main);
        setupOnClickListenerForSearchButton(this);
        setupOnClickListenerForMainButton();
        setupOnClickListenerForSearchCancelButton(this);
        setupOnClickListenerForSearchClearButton(this);
    }

    private void setupOnClickListenerForSearchCancelButton(final MainActivity activity) {
        final Button cancelButton = (Button) findViewById(R.id.button_search_cancel);
        cancelButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {
                final View actionBarView = findViewById(R.id.action_bar_container);
                mIsSearchBarActive = MenuUtils.changeActionBar(activity, actionBarView);
            }
        });
    }


    private void setupOnClickListenerForMainButton() {
        final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
        mainButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {
                toggleNavigationPanel();
            }
        });
    }


    @Override
    public void manageActionBar() {
        setTitle(null);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
    }

    @Override
    public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
        switch (item.getItemId()) {
            case Android.R.id.home:
                toggleNavigationPanel();
                break;

            default:
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    protected void onResume() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastActions.USER_PROFILE);
        filter.addAction(BroadcastActions.NEWS_IMAGE);
        filter.addAction(BroadcastActions.NEWS_HEADLINES);

        registerReceiver(mMainActivityReceiver, filter);
        BangoAgent.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(mMainActivityReceiver);
        super.onPause();
        saveTextSize();
    }

    private void saveTextSize() {
        final ContentResolver resolver = EikonApplication.getAppContext().getContentResolver();
        final ContentValues contentValues = new ContentValues();
        contentValues.put(GenericColumns.TEXT_SIZE, SharedPreferencesManager.getInstance().getTextSize().ordinal());

        SqlArguments argument = SqlArgumentsFactory.generateUserProfileUpdateSqlArguments();
        String where = argument.getWhereClause();
        String[] whereArgs = argument.getWhereArgs();
        resolver.update(UserProfileContentProvider.USER_PROFILE_URI, contentValues, where, whereArgs);
    }

    public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
        NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
    }

    public void onDashboardClicked(final View view) {
        toggleNavigationPanel();

        if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
            return;
        }

        final FragmentManager manager = getSupportFragmentManager();
        final FragmentTransaction transaction = manager.beginTransaction();
        transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = DashboardFragment.getInstance();
        transaction.hide(mActiveFragment);
        transaction.show(mActiveFragment);
        transaction.commitAllowingStateLoss();
        updateActionBarTitle();
    }

    public void onNewsClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onMarketClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onListsClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onBriefcaseClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();
    }

    public void onAlertsClicked(final View view) {
        if(mIsNavigationOpen) {
            toggleNavigationPanel();
        }

        if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
            return;
        }

        FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
        mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
        updateActionBarTitle();

    }

    private void toggleNavigationPanel() {

    if (mDrawerLayout.isDrawerOpen(mDrawer))
            mDrawerLayout.closeDrawer(mDrawer);
        else mDrawerLayout.openDrawer(mDrawer);
        final FragmentStackManager manager = FragmentStackManager.getInstance();

        setNavigationOpen(setNavigationOpen());
    }

    public void updateActionBarTitle() {
        final String title = FragmentStackManager.getInstance().getTopTitle();
        final TextView titleView = (TextView) findViewById(R.id.main_title);
        titleView.setText(title);
    }

    private boolean isFragmentVisible(final String tag) {
        Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
        return fragment != null && tag.equals(fragment.getTag());
    }

    public interface BackPressListener<T extends Fragment> {
        public boolean backPressed(MainActivity fragmentActivity);
    }

    private BackPressListener<Fragment> backPressListener = null;
    public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
            this.backPressListener = backPressListener;
    }


    @Override
    public void onBackPressed() {
        BangoHelper.eventBack();
        if (backPressListener != null) {
            boolean b = false;
            // Making sure we trigger the backPressed event if the listener is the top fragment
            String bplTag = ((Fragment)backPressListener).getTag();
            Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
            String topFragemtnTag = "";
            if (topFragment != null) {
                topFragemtnTag = topFragment.getTag();
                if (bplTag != null && topFragemtnTag != null && bplTag.equals(topFragemtnTag)) {
                    b = backPressListener.backPressed(this);
                }
            }
            if (b) {
                return;
            }

        }

        if (mIsSearchBarActive) {
            MenuUtils.hideSearchView(this);
            mIsSearchBarActive = false;
        } else if (mIsNavigationOpen) {
            toggleNavigationPanel();
        } else if (!FragmentStackManager.getInstance().popTopFragment()) {
            Intent setIntent = new Intent(Intent.ACTION_MAIN);
            setIntent.addCategory(Intent.CATEGORY_HOME);
            setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(setIntent);
        } else {
            Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
            if (topFragment == null) {
                mActiveFragment = DashboardFragment.getInstance();
                ((DashboardFragment)mActiveFragment).refreshDashboard();
            } else if (topFragment instanceof AbsArticlePagerFragment) {
                ((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
            } else if (topFragment instanceof AbsBaseArticleFragment) {
                ((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
            }
        }

        updateActionBarTitle();
    }


    public void setActiveFragment(final Fragment fragment) {
        mActiveFragment = fragment;
    }

    public void setIsSearchBarActive(final boolean isSearchBarActive){
        mIsSearchBarActive = isSearchBarActive;
    }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LIST) {
            if (resultCode == RESULT_OK) {
                Fragment fragment = FragmentStackManager.getInstance().getTopFragment();

                if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
                    DashboardFragment.getInstance().onUpdate();
                } else if (fragment instanceof ListsContainerFragment) {
                    ((ListsContainerFragment) fragment).onUpdate();
                } else if (fragment instanceof ListDetailsFragment) {
                    ((ListDetailsFragment) fragment).onUpdate(data);
                }else if (fragment instanceof AlertsContainerFragment) {
                    ((AlertsContainerFragment) fragment).onUpdate();
                }
            }
        }
    }


    @Override
    public void refreshScreen() {
        Fragment fragment = FragmentStackManager.getInstance().getTopFragment();

        if (fragment == null) { // Implies DashboardFragment
            DashboardFragment.getInstance().refreshScreen();
        } else if (fragment instanceof ListsContainerFragment) {
            ((ListsContainerFragment) fragment).refreshScreen();
        } else if (fragment instanceof ListDetailsFragment) {
            ((ListDetailsFragment) fragment).refreshScreen();
        } else if (fragment instanceof MarketsFragment) {
            ((MarketsFragment) fragment).refreshScreen();
        }

    }

    @Override
    public void retryLoginDelayedData(){
        LoginFragment f = new LoginFragment();
        f.login("delayed");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        FragmentStackManager stackManager = FragmentStackManager.getInstance();
        Fragment topFragment = stackManager.getTopFragment();
        if(topFragment != null){
            if(topFragment instanceof ChartFragment){
                ChartFragment.replaceInstance(((ChartFragment)topFragment), getSupportFragmentManager(), R.id.fragment_container);
            }
        }
    }
}

ナビゲーションドロワーの状態は、ドロワーのレイアウトによって管理されていることに注意してください。 DrawerLayoutとドロワーフラグメントはonCreateメソッドでバインドされます。

問題が発生した場合は、前述の記事を参照してください。

---編集----

以下は、私がアプリで使用したアクティビティです。引き出しトグルを追加する方法を示しています(私が投稿したリンクにもこれが示されています)。

これを現在のアクティビティとマージして、ナビゲーションドロワーを機能させることができるはずです。

public class SampleActivity extends AbsBaseaActivity {

    private Fragment mDrawer;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

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

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerMenuItems = getResources().getStringArray(R.array.home_menu_drawer_titles);
        mDrawer = (fragment) findViewById(R.id.drawer);

        /* Set up the drawer toggle */
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(R.string.activity_title);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(R.string.app_name);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

    }

    /**
     * Backward-compatible version of {@link ActionBar#getThemedContext()} that
     * simply returns the {@link Android.app.Activity} if <code>getThemedContext</code> is unavailable.
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Context getActionBarThemedContextCompat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return getActionBar().getThemedContext();
        } else {
            return this;
        }
    }

    @Override protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
        mDrawer.setItemChecked(0, true);
    }

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

    @Override public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case Android.R.id.home:
            if (mDrawerLayout.isDrawerOpen(mDrawer)) {
                mDrawerLayout.closeDrawer(mDrawer);
            } else {
                mDrawerLayout.openDrawer(mDrawer);
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

エラーが発生している場合は、エラーを投稿してください。

3
athor

Uは、以下のリンクからナビゲーションドロワーのソースオードを取得できます

http://hmkcode.com/Android-creating-a-navigation-drawer/

これをワークスペースにコピーするか、既存のソースコードから新しいAndroidプロジェクトとして開きます。

プロジェクトを右クリック>プロパティ> Javaビルドパス>外部jarを追加>インストールされているAndroid SDKs)から最新のV13サポートライブラリを選択し、順番にjarv13にチェックマークを付けます

もう一度プロジェクト>プロパティ> Android> absライブラリを選択して右クリックします。 [図書館のグーグル]

Uはエラーのない作業プロジェクトを取得します

1
Minto

上記のすべての答えは素晴らしいですが、既存のコードに追加するのは少し難しいので、アニメーションとLayoutInflaterを使用してビューを追加し、フラグメントで使用できるアクティビティにナビゲーションドロワーを削除する新しいクラスを作成しました。

NavigationDrawer.Java

import Android.app.Activity;
import Android.support.constraint.ConstraintLayout;
import Android.util.DisplayMetrics;
import Android.view.LayoutInflater;
import Android.view.animation.Animation;
import Android.view.animation.TranslateAnimation;

import static Android.content.Context.LAYOUT_INFLATER_SERVICE;

public class NavigationDrawer {

//State is the visible state
private Boolean state = false, Transition = false;
private ConstraintLayout mainView;
private ConstraintLayout navigationLayout;
private Animation show, hide;

public NavigationDrawer(Activity activity, ConstraintLayout view) {

    this.mainView = view;

    LayoutInflater layoutInflater = (LayoutInflater) 
activity.getSystemService(LAYOUT_INFLATER_SERVICE);
    navigationLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.nav_drawer, 
mainView, false);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    //Show animation
    show = new TranslateAnimation(-displayMetrics.widthPixels, 0, 0, 0);
    show.setDuration(500);
    show.getFillAfter();
    show.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            Transition = true;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            Transition = false;
            state = true;
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });

    //Hide animation
    hide = new TranslateAnimation(0, -displayMetrics.widthPixels, 0, 0);
    hide.setDuration(500);
    hide.getFillAfter();

    hide.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            Transition = true;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            Transition = false;
            state = false;
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
}

public void toggle() {
    if (!Transition) {
        if (!state) {
            mainView.addView(navigationLayout);
            navigationLayout.startAnimation(show);
        } else {
            navigationLayout.startAnimation(hide);
            mainView.removeView(navigationLayout);
        }
    }
}
}

このクラスを使用するには。

NavigationDrawer navigationDrawer = new 
NavigationDrawer(this,user_activity_main_layout);

//To toggle it
navigationDrawer.toggle();

ここでser_activity_main_layoutは、ルートConstrainLayoutのIDであり、必要に応じて選択できます。これは完璧に機能します。

0
Varun Raj