添加部分到导航抽屉

时间:2015-05-12 06:28:11

标签: android android-fragments android-navigation

我有以下代码:

activity.xml

<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 to display Fragments -->

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- Listview to display slider menu -->

    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/list_background"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

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

MainActivity.java

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

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

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
                .getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
                .getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
                .getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
                .getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
                .getResourceId(4, -1)));
        // What's hot, We will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
                .getResourceId(5, -1), true, "50+"));

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, // nav menu toggle icon
                R.string.app_name, // nav drawer open - description for
                                    // accessibility
                R.string.app_name // nav drawer close - description for
                                    // accessibility
        ) {
            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();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:

            fragment = new HomeFragment();
            break;

        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

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

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

对于我有以下xml的部分:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#FFF" >

    <TextView
        android:id="@+id/navmenusection_label"
        style="?android:attr/listSeparatorTextViewStyle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#BBB"
        android:paddingBottom="7dp"
        android:paddingTop="7dp"
        android:text="Section"
        android:textColor="#FFFFFF"
        android:textSize="18sp" />

</RelativeLayout>

那么如何在导航栏中添加该部分。 ? 我已经更改了NavDrawerListAdapter.java文件:

public class NavDrawerListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<NavDrawerItem> navDrawerItems;

    public NavDrawerListAdapter(Context context,
            ArrayList<NavDrawerItem> navDrawerItems) {
        this.context = context;
        this.navDrawerItems = navDrawerItems;
    }

    @Override
    public int getCount() {
        return navDrawerItems.size();
    }

    @Override
    public Object getItem(int position) {
        return navDrawerItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater) context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
            /*
             * convertView = mInflater.inflate(R.layout.navdrawer_section,
             * parent, false);
             */
        }

        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
        TextView txtCount = (TextView) convertView.findViewById(R.id.counter);

        imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
        txtTitle.setText(navDrawerItems.get(position).getTitle());

        // displaying count
        // check whether it set visible or not
        if (navDrawerItems.get(position).getCounterVisibility()) {
            txtCount.setText(navDrawerItems.get(position).getCount());
        } else {
            // hide the counter view
            txtCount.setVisibility(View.GONE);
        }

        return convertView;
    }

}

convertView = mInflater.inflate(R.layout.navdrawer_section, parent, false);

我把它放在getView()但是我收到了错误。

Logcat:

 FATAL EXCEPTION: main
 Process: com.novumlogic.euphoria, PID: 26846
 java.lang.NullPointerException
    at com.novumlogic.euphoria.adapter.NavDrawerListAdapter.getView(NavDrawerListAdapter.java:59)
    at android.widget.AbsListView.obtainView(AbsListView.java:2338)
    at android.widget.ListView.makeAndAddView(ListView.java:1812)
    at android.widget.ListView.fillDown(ListView.java:698)
    at android.widget.ListView.fillFromTop(ListView.java:759)
    at android.widget.ListView.layoutChildren(ListView.java:1631)
    at android.widget.AbsListView.onLayout(AbsListView.java:2149)
    at android.view.View.layout(View.java:15125)
    at android.view.ViewGroup.layout(ViewGroup.java:4862)
    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:702)
    at android.view.View.layout(View.java:15125)
    at android.view.ViewGroup.layout(ViewGroup.java:4862)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
    at android.view.View.layout(View.java:15125)
    at android.view.ViewGroup.layout(ViewGroup.java:4862)
    at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374)
    at android.view.View.layout(View.java:15125)
    at android.view.ViewGroup.layout(ViewGroup.java:4862)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
    at android.view.View.layout(View.java:15125)
    at android.view.ViewGroup.layout(ViewGroup.java:4862)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
    at android.view.Choreographer.doCallbacks(Choreographer.java:591)
    at android.view.Choreographer.doFrame(Choreographer.java:560)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
    at android.os.Handler.handleCallback(Handler.java:808)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:5333)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
    at dalvik.system.NativeStart.main(Native Method)

我该如何添加该部分?

1 个答案:

答案 0 :(得分:0)

首先删除导致空指针异常的所有更改,然后转到drwer_list_item.xml并为部分添加文本视图,然后转到NavDrawerItem.class并添加:

private String section;

将构造函数更改为:

public NavDrawerItem(String title, int icon,String section){
    this.title = title;
    this.icon = icon;
    this.section= section;
}

您还必须为私人部分实例添加getter和setter:

public String getSection(){
    return this.section;
}

public void setSection(String section){
    this.section = section;
}

然后转到navDrewerListAdapter.class并添加:

TextView txtSection = (TextView) convertView.findViewById(R.id.section);

你要做的最后一件事就是改变你的navDrawerItems.add

navDrawerItems.add(new NavDrawerItem(navMenuTitles[index], navMenuIcons
            .getResourceId(index, -1)));

到此:

navDrawerItems.add(new NavDrawerItem(navMenuTitles[index], navMenuIcons
            .getResourceId(index, -1),"String Section"));
希望这会有所帮助。