Doubt with DrawerLayout and NavigationView when trying to open it from an ImageView

0

In the ActivityMain of my application, I have created a DrawerLayout and a NavigationView which works perfectly and within the menu that is displayed I have put several links to fragment that are changing as you click on they.

So far so good.

I have the problem within a fragment . In this fragment I only show an image that occupies the whole screen and my intention is that when the image is pressed the DrawerLayout is shown with the side menu.

I tried to create an object of class MainActivity to call drawerLayout but this causes an error and I think that's not the solution.

At this moment the code of my fragment is:

   public class FragmentInicio extends Fragment {

        public FragmentInicio() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View v = inflater.inflate(R.layout.fragment_inicio, container, false);
            ImageView logo = (ImageView) v.findViewById(R.id.imageEccaInicio);
            logo.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view){
                    Toast.makeText(view.getContext(), "Se ha tocado la imagen", Toast.LENGTH_LONG).show();
                    //drawerLayout.openDrawer(GravityCompat.START);
                }
            });
            return v;
        }

    }

I also tried to do this from the MainActivity but it also produced an error.

    
asked by Natlum 27.10.2016 в 16:45
source

2 answers

0

In the end it was easier than I thought.

1º In the MainActivity I created a method to open the DrawerLayout

public void openDrawer(){
        drawerLayout.openDrawer(GravityCompat.START);
}

2nd In the Fragment where I have the image when the event occurs onClick I've called the MainActivity method

ImageView logo = (ImageView) v.findViewById(R.id.imageEccaInicio);
        logo.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Toast.makeText(view.getContext(), "Se ha tocado la imagen", Toast.LENGTH_LONG).show();
                ((MainActivity)getActivity()).openDrawer();
            }
        });

Apparently a better way is to create a Listener, but I did not get it. This is the solution that worked for me.

I hope it will be useful, greetings and thanks to Nicol Israel Olvera Acosta

    
answered by 28.10.2016 / 11:53
source
1

A friend listener

public interface DrawerListener {
    void openDrawer();
}

You implement it in your MainActivity and pass it as an argument to the fragment

Fragment frag = new TuFragment();
frag.setDrawerListener(MainActivity.this);

and in the fragment

mDrawerListener.openDrawer();
    
answered by 27.10.2016 в 18:52