Toggle navigation box 'open' on Button / Image click

I created a fragment that is connected to XML containing a single image. The navigation box (using the action bar) is configured inside activity_main.java and works fine. What I want to do is when I click on the image inside the fragment, the navigation box should β€œswitch”.

The following code inside the 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; } 

The null pointer is returned in the following expression:

mDrawerLayout.openDrawer (mDrawer);

+7
android android-fragments navigation-drawer android-actionbar-compat
source share
4 answers

These lines refer to the wrong view:

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

They look for a box in "R.layout.home" because what you inflate and set to a view variable, findViewById () returns null because it does not exist.

If this view is a child of activity_main, you can change them:

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

In addition, I would make these members of the class, not final.

+10
source share

It works when a button is pressed

 mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawer.openDrawer(GravityCompat.START); } }); 

He works with the image. Click

 mImageview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawer.openDrawer(GravityCompat.START); } }); 
+2
source share

I need to use this in your activity:

 final DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); imageViewMenu = (ImageView) findViewById(R.id.imageViewMenu); imageViewMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDrawerLayout.openDrawer(Gravity.START); } }); 

Hope to help!

0
source share
-2
source share

All Articles