Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

android - How do I add navigation drawer to my existing code?

I have an app in which I have a navigation panel with menu buttons on which I want to apply navigation drawer, currently it takes up the entire screen,but I want to restrict it to 3/4th of the screen by applying navigation drawer on it, but i have never touched navigation drawer before so have no clue, any help or guidance will be great.Also went through some documentation and got confused :( Here is my code:

and here is my layout class for navigation panel:

<?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>

Also here is my 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();
         

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a good article to follow for adding a navigation drawer: http://developer.android.com/training/implementing-navigation/nav-drawer.html

Your navigation drawer is showing a blank panel, because the drawer view in your activity_main.xml is a ListView (which you haven't set any data to).

You want to make this view your fragment.

Your activity_main.xml file should look like. Make sure to replace the class on the fragment tag to the correct class of your navigation fragment.

<?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>

Your MainActivity should look something like this:

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 = FragmentStackManag

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...