在导航器中设置ContentView

时间:2014-09-23 14:53:48

标签: java android navigation drawer

我对Android编程很新,我无法在互联网上找到答案。 我在Android Studio中设置了导航抽屉,如果选择了该部分,我想更改内容视图,例如,如果我选择了一个视图"工具"在导航抽屉里,我希望你能看到布局"工具"但你也可以回到导航抽屉。我试图将setContentView放入案例1等,但这给了一个错误。

我为setContentView尝试了这段代码:

public class MainActivity extends Activity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

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

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

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

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            //This is where I thought I could implement the setContentView

            setContentView(R.layout.activity_tools);
            mTitle = "Tools";
            break;
        case 2:
            mTitle = "Weapons";
            break;
        case 3:
            mTitle = "Mobs";
            break;
        case 4:
            mTitle = "Food";
            break;
        case 5:
            mTitle = "Blocks";
            break;
    }
}

1 个答案:

答案 0 :(得分:0)

ContentView不是您想要在抽屉项目选择上更改的内容。 ContentView设置您的活动布局(包含NavigationDrawer视图的布局)。你真正想要的是替换片段。

假设你有一个不同的片段,它有自己的布局,用于导航菜单中的每个项目。在这种情况下,您可以实现类似:

public void onNavigationDrawerItemSelected(int position) {
    Fragment fragment;
    Bundle args = new Bundle();
    String tag;
    switch (position) {
        case 1:
            fragment = new FragmentTools();
            tag = "Tools";
            args.putString(KEY_FRAGMENT_TITLE, tag);
            break;
        case 2:
            fragment = new FragmentWeapons();
            tag = "Weapons";
            args.putString(KEY_FRAGMENT_TITLE, tag);
            break;
        case 3:
            ...
    }
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    fragment.setArguments(args);
    transaction.replace(R.id.fragment_container, fragment, tag);
    transaction.commit();
}

以上只是一个例子。您可以选择要显示的片段并设置其参数。对于cource,它可以是具有不同布局的相同片段。在这种情况下,您可以将布局ID作为参数传递,或者根据其标题在Fragment中选择适当的布局。