在导航抽屉中获取所选项目文本

时间:2015-03-23 17:00:53

标签: android android-fragments navigation-drawer

我在Android Studio中使用内置模板导航Drawer。

我想从导航栏菜单中获取所选项目的文本。

public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
            .commit();
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

最简单的方法是修改回调。

NavigationDrawerFragment内滚动到底部,然后更改NavigationDrawerCallback以包含字符串:

public static interface NavigationDrawerCallbacks {
    void onNavigationDrawerItemSelected(int position, String selectedText);
}

要传递此字符串,您必须修改方法selectItem(item position)以获取字符串。然后在OnItemClickListener onCreateView()中修改它:

mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView row = (TextView) view;
        String selectedText = row.getText().toString();
        selectItem(position, selectedText);
    }
});

继续,将selectItem(int position)修改为:

private void selectItem(int position, String selectedText) {
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position, selectedText);
    }
}

现在你有了所选的菜单文字。