0

我正在使用这个助手类在我的应用程序中创建一个导航抽屉,并且我已经成功地从 json 文件中动态添加数据:

    NavMenuItem createMenu = null;
                NavDrawerItem[] menu = new NavDrawerItem[]{};
                int i = 1;
                for (Post post : PostsActivity.this.posts){
                     createMenu = NavMenuItem.create(i, post.title+i, false, this);
                     menu = new NavDrawerItem[]{createMenu};
                     i++;
                }

NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
            navDrawerActivityConfiguration.setMainLayout(R.layout.activity_drawer);
            navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
            navDrawerActivityConfiguration.setLeftDrawerId(R.id.nav_drawer);
            navDrawerActivityConfiguration.setNavItems(menu);
            navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow);
            navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open);
            navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close);
            navDrawerActivityConfiguration.setBaseAdapter(
                    new NavDrawerAdapter(this, R.layout.listview_drawer_item, menu ));

问题是只posts显示数组中的最后一个数据。如何迭代数组以便将所有数据添加到NavDrawerItem数组中?

这是作者给出的原始示例中将数据添加到数组中的方式:

NavDrawerItem[] menu = new NavDrawerItem[] {
                NavMenuSection.create( 100, "Demos"),
                NavMenuItem.create(101,"List/Detail (Fragment)", "navdrawer_friends", false, this),
                NavMenuItem.create(102, "Airport (AsyncTask)", "navdrawer_airport", true, this), 
                NavMenuSection.create(200, "General"),
                NavMenuItem.create(202, "Rate this app", "navdrawer_rating", false, this),
                NavMenuItem.create(203, "Eula", "navdrawer_eula", false, this), 
                NavMenuItem.create(204, "Quit", "navdrawer_quit", false, this)};
4

1 回答 1

1

尝试这个:

ArrayList<NavDrawerItem> menu = new ArrayList<NavDrawerItem>();
int i = 1;
for (Post post : PostsActivity.this.posts){
     menu.add(NavMenuItem.create(i, post.title+i, false, this));
     i++;
}
NavDrawerItem[] navItems = new NavDrawerItem[menu.size()];
navItems = menu.toArray(navItems);

NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
navDrawerActivityConfiguration.setMainLayout(R.layout.activity_drawer);
navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
navDrawerActivityConfiguration.setLeftDrawerId(R.id.nav_drawer);
navDrawerActivityConfiguration.setNavItems(navItems);
navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow);
navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open);
navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close);
navDrawerActivityConfiguration.setBaseAdapter(
        new NavDrawerAdapter(this, R.layout.listview_drawer_item, navItems ));
于 2013-11-12T22:46:44.660 回答