将标题添加到导航抽屉

时间:2014-06-07 17:57:32

标签: android android-layout navigation

我一直试图在我的导航抽屉中添加标题/部分,但遗憾的是失败了。 我在StackOverFlow中查看了这些问题:

Android Navigation Drawer ListView Headers

Navigation Drawer with Headers/Sections

这就是我要做的事情。 我想制作一个导航抽屉(每行中有图标和文字),并且在某些标题之间(例如在第2项和第6项中)。 如果你告诉我在我的代码中添加/更改的内容,使其成为可能,我将不胜感激。(但更详细的是"覆盖功能X和覆盖功能Y",因为我是初学者,我在尝试将其实施到我的代码时遇到了不好的时间→我今天尝试了6次,但它崩溃了。

MainActivity:

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;

public class MainActivity extends Activity {
    public String[] drawerListViewItems;
    public ListView drawerListView;
    public ActionBarDrawerToggle actionBarDrawerToggle;
    public DrawerLayout drawerLayout;
    TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private List<RowItem> rowItems;
private CustomAdapter adapter;

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

    // organize the title of the navigation drawer
    mTitle = mDrawerTitle = getTitle();

    // get list items from strings.xml
    drawerListViewItems = getResources().getStringArray(
            R.array.Navigation_Drawer);
    // get list icons from the strings
    menuIcons = getResources().obtainTypedArray(R.array.icons);

    // get ListView defined in activity_main.xml
    drawerListView = (ListView) findViewById(R.id.left_drawer);

    // Set the adapter for the list view
    drawerListView.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_listview_item, drawerListViewItems));
    // row items array list "RowItem" it's a class
    rowItems = new ArrayList<RowItem>();
    // adds the icons to each item sync
    for (int i = 0; i < drawerListViewItems.length; i++) {
        RowItem items = new RowItem(drawerListViewItems[i],
                menuIcons.getResourceId(i, -1));
        rowItems.add(items);
    }

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    /*
     * LayoutInflater inflater = getLayoutInflater(); ViewGroup mTop =
     * (ViewGroup)inflater.inflate(R.layout.flats, drawerListView, false);
     * drawerListView.addHeaderView(mTop);
     */

    actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
    drawerLayout, /* DrawerLayout object from line 31 */
    R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
    R.string.drawer_open, /* "open drawer" description */
    R.string.drawer_close /* "close drawer" description */
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
        }
        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
        }
    };

    menuIcons.recycle();

    adapter = new CustomAdapter(getApplicationContext(), rowItems);
    drawerListView.setAdapter(adapter);  
    drawerLayout.setDrawerListener(actionBarDrawerToggle); 
    getActionBar().setDisplayHomeAsUpEnabled(true);

    drawerListView.setOnItemClickListener(new DrawerItemClickListener());

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}   
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    actionBarDrawerToggle.onConfigurationChanged(newConfig);
}   
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
    // true
    // then it has handled the app icon touch event
    if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}   
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    actionBarDrawerToggle.syncState();
}  
private class DrawerItemClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView parent, View view, int position,
            long id) {
        SelectItem(position);
    }   
}

public void SelectItem(int position) {
    // TODO Auto-generated method stub
    switch (position) {
    case 0:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 1:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 2:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 3:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 4:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 5:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 6:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 7:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    case 8:
        setTitle(drawerListViewItems[position]);
        drawerLayout.closeDrawer(drawerListView);
        break;
    default:
        break;
    }   
}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}   
}

CustomAdapter:

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 public class CustomAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;

CustomAdapter(Context context, List<RowItem> rowItem) {
    this.context = context;
    this.rowItem = rowItem;
}

private class ViewHolder {
    ImageView icon;
    TextView title;
}

@Override
public int getViewTypeCount() {
    return super.getViewTypeCount();
}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

LayoutInflater mInflater = (LayoutInflater) context
        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
    convertView = mInflater.inflate(R.layout.list_item, null);
    holder = new ViewHolder();
    holder.icon = (ImageView) convertView.findViewById(R.id.icon);
    holder.title = (TextView) convertView.findViewById(R.id.title);

    RowItem row_pos = rowItem.get(position);
    // setting the image resource and title
    holder.icon.setImageResource(row_pos.getIcon());
    holder.title.setText(row_pos.getTitle());
    convertView.setTag(holder);
} else {
    holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
@Override
public int getCount() {
    return rowItem.size();
}
@Override
public Object getItem(int position) {
    return rowItem.get(position);
}
@Override
public long getItemId(int position) {
    return rowItem.indexOf(getItem(position));

 }

}

RowItem:

  public class RowItem {

private String title;
private int icon;
String ItemName;
public RowItem(String title, int icon) {
    this.title = title;
    this.icon = icon;
}
public String getItemName() {
    return ItemName;
}
public void setItemName(String itemName) {
    ItemName = itemName;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public int getIcon() {
    return icon;
}
public void setIcon(int icon) {
    this.icon = icon;
}
}

drawerlistviewitem.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:padding="2dp" >
    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:contentDescription="desc"
        android:src="@drawable/firstlogo" />
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:text="abccc"
        android:textColor="#000000"
        android:textSize="20sp" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

希望你的答案或问题已经解决了。 但如果没有,您可以尝试https://github.com/AndGitRepo/NavDrawer/tree/master/NavDrawer

的示例

您可以为列表项创建界面。然后在两个类中实现该接口:一个用于列表项,第二个用于列表的Section / Header项。

public class NavMenuSection implements NavDrawerItem {

public static final int SECTION_TYPE = 0;
private int id;
private String label;

private NavMenuSection() {
}

public static NavMenuSection create( int id, String label ) {
    NavMenuSection section = new NavMenuSection();
    section.setLabel(label);
    return section;
}

@Override
public int getType() {
    return SECTION_TYPE;
}

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

@Override
public boolean isEnabled() {
    return false;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Override
public boolean updateActionBarTitle() {
    return false;
}

}

列表项的另一个类是

public static final int ITEM_TYPE = 1 ;

private int id ;
private String label ; 
private int icon ;
private boolean updateActionBarTitle ;

private NavMenuItem() {
}

public static NavMenuItem create( int id, String label, String icon, boolean updateActionBarTitle, Context context ) {
    NavMenuItem item = new NavMenuItem();
    item.setId(id);
    item.setLabel(label);
    item.setIcon(context.getResources().getIdentifier( icon, "drawable", context.getPackageName()));
    item.setUpdateActionBarTitle(updateActionBarTitle);
    return item;
}

@Override
public int getType() {
    return ITEM_TYPE;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public int getIcon() {
    return icon;
}

public void setIcon(int icon) {
    this.icon = icon;
}

@Override
public boolean isEnabled() {
    return true;
}

@Override
public boolean updateActionBarTitle() {
    return this.updateActionBarTitle;
}

public void setUpdateActionBarTitle(boolean updateActionBarTitle) {
    this.updateActionBarTitle = updateActionBarTitle;
}

现在更新适配器代码

public class NavDrawerAdapter extends  ArrayAdapter<NavDrawerItem>{

private LayoutInflater inflater;

public NavDrawerAdapter(Context context, int textViewResourceId, NavDrawerItem[] objects ) {
    super(context, textViewResourceId, objects);
    this.inflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null ;
    NavDrawerItem menuItem = this.getItem(position);
    if ( menuItem.getType() == NavMenuItem.ITEM_TYPE ) {
        view = getItemView(convertView, parent, menuItem );
    }
    else {
        view = getSectionView(convertView, parent, menuItem);
    }
    return view ;
}

public View getItemView( View convertView, ViewGroup parentView, NavDrawerItem navDrawerItem ) {

    NavMenuItem menuItem = (NavMenuItem) navDrawerItem ;
    NavMenuItemHolder navMenuItemHolder = null;

    if (convertView == null) {
        convertView = inflater.inflate( R.layout.navdrawer_item, parentView, false);
        TextView labelView = (TextView) convertView
                .findViewById( R.id.navmenuitem_label );
        ImageView iconView = (ImageView) convertView
                .findViewById( R.id.navmenuitem_icon );

        navMenuItemHolder = new NavMenuItemHolder();
        navMenuItemHolder.labelView = labelView ;
        navMenuItemHolder.iconView = iconView ;

        convertView.setTag(navMenuItemHolder);
    }

    if ( navMenuItemHolder == null ) {
        navMenuItemHolder = (NavMenuItemHolder) convertView.getTag();
    }

    navMenuItemHolder.labelView.setText(menuItem.getLabel());
    navMenuItemHolder.iconView.setImageResource(menuItem.getIcon());

    return convertView ;
}

public View getSectionView(View convertView, ViewGroup parentView,
        NavDrawerItem navDrawerItem) {

    NavMenuSection menuSection = (NavMenuSection) navDrawerItem ;
    NavMenuSectionHolder navMenuItemHolder = null;

    if (convertView == null) {
        convertView = inflater.inflate( R.layout.navdrawer_section, parentView, false);
        TextView labelView = (TextView) convertView
                .findViewById( R.id.navmenusection_label );

        navMenuItemHolder = new NavMenuSectionHolder();
        navMenuItemHolder.labelView = labelView ;
        convertView.setTag(navMenuItemHolder);
    }

    if ( navMenuItemHolder == null ) {
        navMenuItemHolder = (NavMenuSectionHolder) convertView.getTag();
    }

    navMenuItemHolder.labelView.setText(menuSection.getLabel());

    return convertView ;
}

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public int getItemViewType(int position) {
    return this.getItem(position).getType();
}

@Override
public boolean isEnabled(int position) {
    return getItem(position).isEnabled();
}


private static class NavMenuItemHolder {
    private TextView labelView;
    private ImageView iconView;
}

private class NavMenuSectionHolder {
    private TextView labelView;
}}

然后从主要活动添加列表项作为部分和/或项目

 NavDrawerItem[] menu = new NavDrawerItem[] {
            NavMenuSection.create( 100, "Logged in user details"),
            //NavMenuItem.create(101,"List/Detail (Fragment)", "navdrawer_friends", true, this),
            //NavMenuItem.create(102, "Airport (AsyncTask)", "navdrawer_airport", false, this),
            //NavMenuSection.create(200, "General"),
            NavMenuItem.create(202, "Rate this app", "drawer_shadow", false, this),
            NavMenuItem.create(203, "Nav", "drawer_shadow", false, this),
            NavMenuItem.create(204, "Quit", "drawer_shadow", false, this)};

    NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
    navDrawerActivityConfiguration.setMainLayout(R.layout.activity_nav_drawer);
    navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
    navDrawerActivityConfiguration.setLeftDrawerId(R.id.left_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.navdrawer_item, menu ));

对于完整代码,您可以使用github链接。因为我不能在这里粘贴完整的代码。