【问题标题】:The issue with toolbar and navigation View工具栏和导航视图的问题
【发布时间】:2017-09-06 14:19:50
【问题描述】:

我有一个活动,里面有工具栏和导航视图。

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 中选择项目时,会打开新的 Fragment。 当出现第二个片段时,我在里面使用

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

出现了向上箭头,但是当我单击此向上箭头时会打开 NavigationVIEW!!! 在 onOptionsItemSelected 的片段中我有

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);
}

【问题讨论】:

    标签: android android-fragments toolbar


    【解决方案1】:

    您应该覆盖 onOptionsItemSelected(MenuItem item) 并且应该在 onCreate(Bundle savedInstanceState) 内部调用 setHasOptionsMenu(true)

     @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....
    

    【讨论】:

      【解决方案2】:

      使用这个完整的例子。

       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();
          }
      
      }
      

      您的 Main Activity 必须扩展 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>
      

      【讨论】:

      • 可以用我的代码来完成吗?我的代码有什么问题?
      猜你喜欢
      • 1970-01-01
      • 2018-04-19
      • 2018-08-12
      • 2017-03-15
      • 2020-10-17
      • 2019-01-26
      • 2015-12-09
      • 2011-10-20
      • 2021-12-03
      相关资源
      最近更新 更多