Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Navigation Drawer 'open' on Button/ Image click

I've created a fragment that is hooked to an XML containing one image view. A navigation drawer (using actionbar compat) is set up inside activity_main.java and is working fine. What i'm wanting to do is, when I tap on the image inside the fragment, the navigation drawer should 'toggle open'.

The following code inside onCreateView method returns a null pointer:

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState)
            {   

                View view=inflater.inflate(R.layout.home, container, false);

                ImageView img=(ImageView)view.findViewById(R.id.imageView1);

               // Defined inside activity_main.xml
                final LinearLayout mDrawer = (LinearLayout) view.findViewById(R.id.drawer); 

               // Defined inside activity_main.xml
                final DrawerLayout mDrawerLayout = (DrawerLayout)view.findViewById(R.id.drawer_layout); 

                img.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                     mDrawerLayout.openDrawer(mDrawer);

                    }
                });

                return view;    
                }

A null pointer is returned at the following statement:

mDrawerLayout.openDrawer(mDrawer);

like image 375
rajagrawal Avatar asked Mar 12 '14 04:03

rajagrawal


2 Answers

These lines are referencing the wrong view:

final LinearLayout mDrawer = (LinearLayout) view.findViewById(R.id.drawer); 
final DrawerLayout mDrawerLayout = (DrawerLayout)view.findViewById(R.id.drawer_layout);

They are looking for the drawer in 'R.layout.home' because that's what you inflate and set to the view variable, findViewById() returning null because it's not there.

If this view is a child of activity_main then you should be able to change these to:

final LinearLayout mDrawer = (LinearLayout) getActivity().findViewById(R.id.drawer); 
final DrawerLayout mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);

Additionally, I'd make these class members and not final.

like image 158
Steven Trigg Avatar answered Sep 30 '22 18:09

Steven Trigg


It works on Button click

mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            drawer.openDrawer(GravityCompat.START);

        }
    });

It works on Image click

mImageview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            drawer.openDrawer(GravityCompat.START);

        }
    });
like image 26
Maksudul Hasan Raju Avatar answered Sep 30 '22 18:09

Maksudul Hasan Raju