我在Android应用程序中添加了滑块菜单。但点击侧边栏

时间:2016-04-26 04:59:25

标签: android

我在Android应用中添加了滑块菜单。但点击侧边菜单后无法打开。单击侧面菜单后,它不是打开列表。当我调试我发现适配器= NULL& mdrawertoggle = NULL。

我正在添加代码,如果有人,请提供解决方案。 谢谢。 Attached image is showing side menu but unable to get list after clicking 。 MainActivity

public class MainActivity extends Activity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    //  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 adater ;


    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();
    // data of json url
    private static final String url = "http://milagro.in/wip/apps/n/THDC2.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();

        // Enabling Up / Back navigation
        //actionBar.setDisplayHomeAsUpEnabled(true);
        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);
        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();
        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.drawerLayout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Profile
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // About
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Emi Calculator
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Currency Converter
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // PayInstallments/EMI
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // Social Feed
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        // Feedback
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
        //Settings
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));

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

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

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

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

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.menu, //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);
        }
        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("tata_project_name"));
                                movie.setThumbnailUrl(obj.getString("project_logo_url"));
                                movie.setParkingUrl(obj.getString("parking"));
                                movie.setPowerbackupUrl(obj.getString("powerbackup"));
                                movie.setFitnessUrl(obj.getString("fitness"));
                                movie.setLiftUrl(obj.getString("lift"));
                                movie.setParkUrl(obj.getString("park"));
                                movie.setSecurityUrl(obj.getString("security"));
                                movie.setSwimmingUrl(obj.getString("swimming"));
                                movie.setTypology(obj.getString("project_Typology"));
                                movie.setPrice(obj.getString("price"));
                                // adding movie to movies array
                                movieList.add(movie);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

    }

    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);
    }




    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new Profile();
                break;
            case 1:
                fragment = new About();
                break;
            case 2:
                fragment = new EMICalculator();
                break;
            case 3:
                fragment = new CurrencyConverter();
                break;
            case 4:
                fragment = new PayInstallment();
                break;
            case 5:
                fragment = new SocialFeed();
                break;
            case 6 :
                fragment =new Feedback();
                break;
            case 7:
                fragment =new Settings();
            break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container_frame, 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);
    }

    @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);
    }


    public void bottomMenuClick(View v)
    {
        int pos = Integer.parseInt(v.getTag().toString());

        switch (pos)
        {
            case 1: // enquiry screen
                startActivity(new Intent(MainActivity.this,Enquiry.class));
                break;
            case 2: // contact screen
                startActivity(new Intent(MainActivity.this, Contact.class));
                break;
            case 3: // Instant Call Back screen
                startActivity(new Intent(MainActivity.this, CallBack.class));
                break;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity"
            android:id="@+id/app_name"
            >


            <android.support.v4.widget.DrawerLayout
                android:id="@+id/drawerLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"

                >


            <FrameLayout
                android:id="@+id/container_frame"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"/>

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

            </android.support.v4.widget.DrawerLayout>
                <ListView
                    android:id="@+id/list"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:divider="@color/list_divider"
                    android:dividerHeight="1dp"
                    android:listSelector="@drawable/list_row_selector"
                    android:background="@color/list_background"/>

               <!-- <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_below="@+id/content_frame"
                      >-->
         <!--   <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"></LinearLayout>

          <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"></LinearLayout>

           <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"></LinearLayout>

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"

                android:layout_weight="1">

                    <Button
                        android:id="@+id/MyButton"

                        android:layout_width="370dp"
                        android:layout_height="30dp"
                        android:layout_marginLeft="20dp"
                        android:layout_marginRight="20dp"
                        android:background="#01458e"
                        android:textColor="#FFFFFF"
                        android:text="@string/button_text"></Button>


            </LinearLayout>
            </LinearLayout>-->
              <!-- </LinearLayout>-->


        <!--
            <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">

                &lt;!&ndash; Framelayout to display Fragments &ndash;&gt;
                <FrameLayout
                    android:id="@+id/frame_container"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                &lt;!&ndash; Listview to display slider menu &ndash;&gt;
                <ListView
                    android:id="@+id/list_slidermenu"
                    android:layout_width="240dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="start"
                    android:choiceMode="singleChoice"
                    android:divider="@color/list_divider"
                    android:dividerHeight="1dp"
                    android:listSelector="@drawable/list_selector"
                    android:background="@color/list_background"/>
            </android.support.v4.widget.DrawerLayout>-->
        <!--<RelativeLayout
                android:id="@+id/topLay"
                android:layout_width="match_parent"
                android:layout_height="@dimen/topLayHt"
                android:layout_alignParentTop="true"
                android:background="@drawable/header_bg">
            &lt;!&ndash;<ImageView
                android:id="@+id/settingBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/setting_btn_highlight"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="@dimen/setting_btn_mg_rt"
                android:clickable="true"
                android:onClick="settingClick"
                android:visibility="visible"/>

                <ImageView
                    android:id="@+id/menu_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/menu_btn_highlight"
                    android:layout_marginLeft="@dimen/menu_btn_mg_lft"

                    android:clickable="true"
                    android:onClick="menuClick"/>
            <ImageView
                android:id="@+id/homeBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/home_btn_highlight"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="@dimen/home_btn_mg_rt"
                android:clickable="true"
                android:onClick="homeClick"
                android:visibility="gone"/>

            <ImageView
                android:id="@+id/backBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/back_btn_highlight"
                android:layout_centerVertical="true"
                android:layout_marginLeft="@dimen/back_btn_mg_lft"
                android:clickable="true"
                android:onClick="backClick"
                android:visibility="gone"/>&ndash;&gt;
        </RelativeLayout>-->

            <include
                android:id="@+id/menu_lay"
                layout="@layout/bottom_layout"  />

        </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);
        }

        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;
    }

}

drawerlist_item.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:background="@drawable/list_selector">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="25dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:contentDescription="@string/desc_list_item_icon"
        android:src="@drawable/ic_home"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/icon"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="@color/list_item_title"
        android:gravity="center_vertical"
        android:paddingRight="40dp"/>

    <TextView android:id="@+id/counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/counter_bg"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="8dp"
        android:textColor="@color/counter_text_color"/>

</RelativeLayout>

Navdraweritem.java

public class NavDrawerItem {

    private String title;
    private int icon;
    private String count = "0";
    // boolean to set visiblity of the counter
    private boolean isCounterVisible = false;

    public NavDrawerItem(){}

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

    public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){
        this.title = title;
        this.icon = icon;
        this.isCounterVisible = isCounterVisible;
        this.count = count;
    }

    public String getTitle(){
        return this.title;
    }

    public int getIcon(){
        return this.icon;
    }

    public String getCount(){
        return this.count;
    }

    public boolean getCounterVisibility(){
        return this.isCounterVisible;
    }

    public void setTitle(String title){
        this.title = title;
    }

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

    public void setCount(String count){
        this.count = count;
    }

    public void setCounterVisibility(boolean isCounterVisible){
        this.isCounterVisible = isCounterVisible;
    }
}

2 个答案:

答案 0 :(得分:1)

首先,您必须将整个视图放在这样的抽象布局中

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical">

<include
    layout="@layout/activity_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/activity_main_drawer"/>
</android.support.v4.widget.DrawerLayout>

此处活动布局是包含所有视图的主要布局

答案 1 :(得分:1)

activity_main.xml应该是这样的:

     <android.support.v4.widget.DrawerLayout
            android:id="@+id/drawerLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            xmlns:android="http://schemas.android.com/apk/res/android">


            <FrameLayout
                android:id="@+id/container_frame"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"/>

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


                <ListView
                    android:id="@+id/list"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:divider="@color/list_divider"
                    android:dividerHeight="1dp"
                    android:listSelector="@drawable/list_row_selector"
                    android:background="@color/list_background"/>
  </android.support.v4.widget.DrawerLayout>