工具栏和导航视图的问题

时间:2015-09-16 09:08:13

标签: android android-fragments toolbar

我有一个活动,里面有工具栏和navigationView。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_page_activity);
    getFragment(new MainFragment());
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
    mNavigationView.setNavigationItemSelectedListener(this);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_widget);
    drawerToggle
            = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
    mDrawerLayout.setDrawerListener(drawerToggle);
}
    @Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    Log.i("StartPageActivity", "onPostCreate");
    drawerToggle.syncState();
}

首次启动活动时称为Main Fragment。 当我在NavigationView中选择项目时打开新的片段。 当出现第二个片段时,我在里面使用

ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
    a.setDisplayHomeAsUpEnabled(true);

出现向上箭头,但是当我点击此向上箭头打开NavigationVIEW !!! inOptionsItemSelected里面的片段我有

case android.R.id.home:{
            Log.i("One", "Dude");
          }

该程序不符合此代码。它没有达到它。我认为onCreate(活动)里面的问题。也许它在ActionBarDrawerToggle,NavigationView和Toolbar之间发生冲突。

添加第二个片段

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.reminder_list_fragment, container, false);
    getActivity().setTitle("Fragment1");
    mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
    //{RecyclerAdapter}
    ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
    a.setDisplayHomeAsUpEnabled(true);
    a.setHomeButtonEnabled(true);
    return v;
}
@Override
public void onResume() {
    super.onResume();
    mRecyclerView.getAdapter().notifyDataSetChanged();
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.reminder_toolbar, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    Log.d("Testing", "ID == " + id);
    switch (id) {
        case R.id.add_information : {
            Forget f = new Forget();
            ForgetLab.get(getActivity()).addForget(f);
            FragmentManager fm = getFragmentManager();
            Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ReminderFragment.EXTRA_FORGET_ID, f.getId());
            if (mFragment != null) {
                mFragment = new ReminderPagerFragment();
                mFragment.setArguments(bundle);
                fm.beginTransaction().addToBackStack(null)
                        .replace(R.id.fragment_container, mFragment)
                        .commit();
            }
            return true;
        }
        case android.R.id.home:{
            Log.i("One", "Dude");
          }
    }
    return super.onOptionsItemSelected(item);
}

2 个答案:

答案 0 :(得分:3)

您应该在setHasOptionsMenu(true)

内调用onCreate(Bundle savedInstanceState) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { getActivity().onBackPressed(); } return super.onOptionsItemSelected(item); } I hope this works....
compile 'com.google.http-client:google-http-client-android:1.9.0-beta'

答案 1 :(得分:1)

使用此完整示例。

 public abstract class BaseActivity extends AppCompatActivity{
    protected Toolbar toolbar;
    protected User mMe;
    protected DrawerLayout mDrawerLayout;
    protected ActionBarDrawerToggle drawerToggle;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        mMe = SessionUtils.getUser();
        if (mMe == null) {
            return;
        }
        initToolbar();
        initInstances();

    }

    private void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    private void initInstances() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        if (mDrawerLayout != null) {
            final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
            ImageView profileImage = (ImageView) navigationView.findViewById(R.id.profileImage);
            profileImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.launchProfileActivity(BaseActivity.this, SessionUtils.getUser());
                }
            });
            TextView name = (TextView) navigationView.findViewById(R.id.name);
            final String fullName = StringUtils.getFullName(mMe.firstName, mMe.lastName);
            name.setText(fullName);
            GlideUtils.load(profileImage, mMe.getImage(), GlideUtils.getCircularFallbackDrawable(this, fullName), new CircleTransformGlide(this));

            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {

                    int itemId = menuItem.getItemId();
                    switch (itemId) {
                        case R.id.messages:
                            ActivityUtils.launchMessagesFragment(BaseActivity.this);
                            LogUtils.LOGD(">>Menu", "Messages");
                            break;
//                        case R.id.notification:
//                            LogUtils.LOGD(">>Menu", "Notification");
//                            break;
                        case R.id.friends:
                            LogUtils.LOGD(">>Menu", "find friends");
                            ActivityUtils.launchFriendsActivity(BaseActivity.this);
                            break;
                        case R.id.termsOfService:
                            ActivityUtils.launchTermsOfServiceFragment(BaseActivity.this);
                            break;
                        case R.id.friendsRrequests:
                            LogUtils.LOGD(">>Menu", "friendsRrequests");
                            ActivityUtils.launchFriendsRequests(BaseActivity.this);
                            break;
                        case R.id.logout:
                            LogUtils.LOGD(">>Menu", "Logout");
                            DialogUtils.LogoutConfirmDialogFragment logoutConfirmDialogFragment = new DialogUtils.LogoutConfirmDialogFragment();
                            logoutConfirmDialogFragment.show(getSupportFragmentManager(), "Logout Confirmation Fragment");
//                            LoginManager.reset(BaseActivity.this);
                            break;
                    }
//                    menuItem.setChecked(true);
//                    if (R.id.friends == itemId) {
//                        mDrawerLayout.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                mDrawerLayout.closeDrawers();
//                            }
//                        }, 1000);
//                    } else {
//                        mDrawerLayout.closeDrawers();
//                    }
                    return true;
                }
            });
            drawerToggle = new DrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name, new DrawerToggleListener() {
                @Override
                public void OnDrawerClose() {

                }

                @Override
                public void OnDrawerOpen() {

                }
            });
            mDrawerLayout.setDrawerListener(drawerToggle);


            final ActionBar supportActionBar = getSupportActionBar();
            if (supportActionBar != null) {
                supportActionBar.setHomeButtonEnabled(true);
                supportActionBar.setDisplayHomeAsUpEnabled(true);
            }
        }
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (drawerToggle != null)
            drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (drawerToggle != null)
            drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return (drawerToggle != null && drawerToggle.onOptionsItemSelected(item)) || super.onOptionsItemSelected(item);

    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private static class DrawerToggle extends ActionBarDrawerToggle {
        DrawerToggleListener mToggleListener;

        public DrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes, DrawerToggleListener toggleListener) {
            super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
            mToggleListener = toggleListener;
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            mToggleListener.OnDrawerClose();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            mToggleListener.OnDrawerOpen();
        }
    }

    private static abstract class DrawerToggleListener {
        public abstract void OnDrawerClose();

        public abstract void OnDrawerOpen();
    }

}

您的主要活动必须扩展BaseActivity

public class MainActivity extends BaseActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!LoginManager.isFirstFlowFinished(this)) {
        LoginManager.launchCurrentFragment(this);
        finish();
        return;
    }
    Intent intent = getIntent();
    handleIntent(intent);
    setContentView(R.layout.activity_main_new);
    LogUtils.LOGD(">>Intent", "onCreate");
}

@Override
public void onResume() {
    super.onResume();
    LocationTracker.promptIfNeededForEnableLocation(this);
    CommonUtils.checkIfPlayServicesNeedToUpdate(this);
    AppEventsLogger.activateApp(this);
}

@Override
protected void onPause() {
    super.onPause();
    AppEventsLogger.deactivateApp(this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_search_icon:
            ActivityUtils.launchSearchActivity(this);
            break;
    }
    return true;
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    LogUtils.LOGD(">>Intent", "on handle Intent");
    handleIntent(intent);
}

}

这是activity_main_new.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:minHeight="?actionBarSize"
        android:background="?colorPrimary"
        app:layout_collapseMode="pin"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >
        <TextView
            android:textColor="@color/white"
            android:textSize="18sp"
            android:textStyle="bold"
            android:text="Friends Locator"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        </android.support.v7.widget.Toolbar>

    <fragment
        android:orientation="vertical"
        android:id="@+id/viewPager"
        android:name="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
        android:tag="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_header"

    app:itemIconTint="@color/nav_item_icon_tint_color"
    app:itemTextColor="@color/nav_item_text_color"
    app:menu="@menu/navigation_drawer_items" />

和导航菜单项如下:

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

<group android:checkableBehavior="none">

    <item
        android:id="@+id/friends"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/friends_caps" />
    <item
        android:id="@+id/messages"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/messages" />
    <item
        android:id="@+id/friendsRrequests"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/friendsRequests" />
   <!-- <item
        android:id="@+id/notification"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/notifications" />-->

    <!--<item-->
        <!--android:id="@+id/about"-->
        <!--android:icon="@drawable/ic_navigation_chevron_right"-->
        <!--android:title="@string/about" />-->
    <item
        android:id="@+id/termsOfService"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/terms_of_service" />

    <item
        android:id="@+id/logout"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/log_out" />
</group>