android - NavigationDrawer 的多个 Activity (不是 fragment )。如何显示当前选中的Activity?

标签 android navigation-drawer

在决定我们将使用抽屉导航或汉堡菜单之前,我有一个包含很多 Activity 的应用程序。我不想使用 fragment 重做整个应用程序,所以我决定采用此答案中使用的方法: Same Navigation Drawer in different Activities

编辑:现在,这个 https://stackoverflow.com/a/23477100/1371585

然后我创建了一个名为 NavDrawerBaseActivity 的基础 Activity 。这是代码:

    public class NavDrawerBaseActivity extends MyBaseActivity {

    public DrawerLayout mNavDrawerLayout;
    public ListView mDrawerList;
    public String[] mMenuItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.navdrawer_activity);

        mNavDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mMenuItems = getResources().getStringArray(R.array.optionsmenu_array);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mMenuItems);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener(this));

        super.onCreate(savedInstanceState);
    }

    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {

        private DrawerItemClickListener(Context context) {
            mContext = context;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            String textClicked = ((TextView) view).getText().toString();
            view.setSelected(true);

            if (textClicked.equalsIgnoreCase(mContext
                    .getString(R.string.optionsmenu_library))) {


                Intent libraryIntent = new Intent(mContext,
                        LibraryActivity.class);
                libraryIntent.putExtra("navdrawerposition", position);
                startActivity(libraryIntent);
                mNavDrawerLayout.closeDrawers();
                mDrawerList.setItemChecked(position, true); //Not working


            } else if (textClicked.equalsIgnoreCase(mContext
                    .getString(R.string.optionsmenu_settings))) {
                // TODO: open activity and close the drawer
            } else if (textClicked.equalsIgnoreCase(mContext
                    .getString(R.string.optionsmenu_logout))) {
                // TODO: open activity and close the drawer
            } 
        }

        private Context mContext;
    }
}

这里是布局文件navdrawer_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    >

    <FrameLayout
        android:id="@+id/activity_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <!-- The navigation drawer -->

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" 
        />


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

每个 Activity 都扩展了 NavDrawerBaseActivity 并且不使用 setContentView,如下所示:

 public class LibraryActivity extends NavDrawerBaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Not setting content view here, since its already set in
        // NavDrawerBaseActivity
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.activity_frame);
        // Inflating the Camera activity layout
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View activityView = layoutInflater
                .inflate(R.layout.library_page, null, false);
        // Adding the custom layout of this activity to frame layout set in
        // NavDrawerBaseActivity.
        frameLayout.addView(activityView);


//      Only this part of the code is doing what I want.

//      int drawerSelectedPosition = getIntent().getIntExtra(mNavDrawerPosExtraName, -1);
//      if(drawerSelectedPosition > -1){
//          mDrawerList.setItemChecked(drawerSelectedPosition, true);
//      }
    }

}

我的问题:如何正确突出显示 NavDrawer View 中的当前 Activity ? mDrawerList.setItemChecked(position, true); 在启动 Intent 之前或启动之后不起作用。

奇怪的部分是:如果我当前在 Activity1 中,请打开 NavDrawer 并选择 Activity2。我登陆 Activity2,打开 NavDrawer,发现“Activity2”未被选中。我单击“后退”按钮,进入 Activity1,打开 NavDrawer 并看到“Activity2”已被选中。

这意味着 setItemChecked 有效,但在启动的新 Activity 中无效。

目前,我将位置作为 Intent extra 传递,并专门设置选中的位置,如 LibraryActivity 中的注释部分。 这可行,但似乎可以解决。请告诉我在 NavDrawerBaseActivity 类中而不是在每个扩展它的 Activity 中是否有正确/更好的方法来做到这一点。

最佳答案

不要在每个 Activity 中都放置抽屉导航,这违背了扩展 NavDrawerBaseActivity 类的目的。因为所有其他 Activity 都扩展了这个基类,所以它们应该自动继承它的所有功能。因此,只将抽屉放在 NavDrawerBaseActivity 中。然后,在抽屉的 xml 中,您可以指定每个按钮的操作,例如:

<Button
        style="@style/drawerBtn"
        android:id="@+id/activity1Btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick">

或者简单地在你的抽屉上设置一个 onClick 监听器,比如:

myDrawer.setOnClickListener().........etc

然后在您的 onClick 处理程序中(在 NavDrawerBaseActivity 类中)您可以简单地检查哪个按钮被按下并打开关联的 Activity ,例如:

//remember, if you used the onClickListener you have to use @Override at the top of this function
public void onClick(View item) {

    //lets see which button on the drawer was pressed....item is the item that triggered the click
    switch (item.getId()) {
        case R.id.activity1Btn:
            Intent intent1 = new Intent(this, Activity1.class);
            startActivity(intent1);
            break;
        case R.id.activity2Btn:
            Intent intent2 = new Intent(this, Activity2.class);
            startActivity(intent2);
            break;
        case R.id.activity3Btn:
            Intent intent3 = new Intent(this, Activity3.class);
            startActivity(intent3);
            break;
    }
}

请记住,Activity1、Activity2、Activity3 必须扩展 NavDrawerBaseActivity,然后必须扩展 Activity 或扩展另一个类,后者又扩展 Activity……等等。然后,您还可以在此开关中设置诸如 mDrawerList.setItemChecked(position, true) 之类的内容。所以简而言之,让所有抽屉的事情只发生在这个类中,并通过扩展它来简单地“实现”这个类,记住这个类包含所有“子”类/Activity 共有的所有功能,它们都继承了这个行为

编辑:

如果您想突出显示抽屉中的项目,则必须在项目上使用 setSelected(true)。如果您愿意,可以通过在可绘制对象文件夹中创建选择样式来定义自定义选择状态。然后将此样式设置为列表项示例的背景:

<!-- drawable/myStyles.xml-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@color/blue"/> <!--item selected state--> 
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@color/blue"/> <!--item selected state--> 
    <item android:state_enabled="true" android:state_selected="true" android:drawable="@color/blue"/> <!--item selected state--> 
    <item android:state_focused="false" android:state_pressed="false" android:drawable="@color/gray"/> <!--item NOT selected state--> 
</selector>

和你的抽屉里的元素:

<LinearLayout
    android:id="@+id/my_drawer_item"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/myStyles">

然后在您的 switch/if-else 语句中将所选项目设置为 myNewSelectedView.setSelected(true)。您可能必须手动取消选择旧的,例如 myOldSelectedItem.setSelected(false)

然后在切换/if-else 语句的位置单击/选择监听器:

 @Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
     view.setSelected(true)  

     //....the rest of your code here
}

最后,我建议您先尝试这个,因为如果您使用普通的 listView,这将是最简单的方法:

<ListView android:id="@+id/my_list"
    android:choiceMode="singleChoice" 
    android:listSelector="@android:color/blue" />

编辑2:

现在要保留所选项目的状态...所以似乎抽屉上的每个 Action 都会重新实例化基类,这并不理想。我们需要以某种方式保留实例状态,以便它几乎充当单例。我已经尝试覆盖 onSaveInstanceState 并使用 singleInstance 启动器状态,但它们没有用。因此,在此期间,我提出了将内存中的当前选择保存为静态变量的解决方案:

private static int mCurrentSelectionIndex = 0; //this is defined at the top of your class with your default selected screen ie the first item in the list.

//then in setContentView after assigning the drawer layout you set the currentSelection
@Override
public void setContentView(final int layoutResID) {
    //...... first assign the layouts ie mDrawerList = findViewByLayout(R.id.myDrawerList) etc

    mDrawerList.setSelection(mCurrentSelectionIndex); 
      // OR:
    mDrawerList.setItemChecked(mCurrentSelectionIndex, true);
}

//then in onClick()
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    mCurrentSelection = position;
    item.setSelected(true);
}

关于android - NavigationDrawer 的多个 Activity (不是 fragment )。如何显示当前选中的Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27312813/

相关文章:

android - 抽屉导航在单击菜单项时不会切换 fragment

android - 使用抽屉导航的应用程序的 Robotium UI 测试

Android:如何将 Google+ 个人资料图片和封面照片放入抽屉导航

android - 将数据从 Activity 传回已创建的 fragment

android - bouncycaSTLe 中的 NoSuchMethodError

java - 在 Java 中直接比较 2 float/double 是否安全?

android - 如何验证 robotium 中的 View 或布局

java - android:installLocation ="preferExternal"和 WRITE_EXTERNAL_STORAGE 权限

android - WebRTC : gclient runhooks not working

Angular 2 Material 2 Sidenav 工具栏像抽屉导航一样折叠