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