Ad

SetOnClickListener In An IF Statement Not Detecting Clicks

- 1 answer

I'm creating an app that has a toggle-button in the toolbar that makes an appbar drop down.The problem is that I want the appbar to retract back up when I press anywhere on the screen, but it doesn't detect the clicks on the screen.

Edit This is what the dropdown looks like: https://i.imgur.com/dFg0L3v.gif
Right now I'm simply hiding and showing the bar instead of animating it for simplicity.

I've tried to set an OnClickListener to the underlying layout (the coordinatorlayout) when the dropdown is opened, but it's not detecting any clicks.

Code
I'm using XML tags to detect if the appbar is either closed or opened on the moment of the click, default in XML file is "off".

    public boolean onOptionsItemSelected(MenuItem item) {

        final View view = getView();

        final AppBarLayout yearBar = view.findViewById(R.id.yearbar);
        final CoordinatorLayout cLayout = view.findViewById(R.id.main_content);

        switch (item.getItemId()) {
            case R.id.year_dropdown:
                if (yearBar.getTag().toString().trim().equals("on")) {
                    yearBar.setVisibility(View.GONE);
                    yearBar.setTag("off");

                } else if (yearBar.getTag().toString().trim().equals("off")) {
                    yearBar.setVisibility(View.VISIBLE);
                    yearBar.setTag("on");

                    cLayout.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            yearBar.setVisibility(View.GONE);
                            yearBar.setTag("off");
                            Toast.makeText(getActivity(),"Click detected!", Toast.LENGTH_LONG).show();
                        }
                    });

                }
                return true;

            case R.id.settings:
                // Open settings
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

I think that the problem lies in the fact that I'm setting the OnClickListener in the else-if statement, but I've got no idea how else I could set the OnClickListener to only be active when the dropdown has opened. Any suggestions?

Thanks in advance!

Ad

Answer

You can declare a Boolean variable to holds the state of dropDown. set onClick outside of the if statement and check state in it. It's the simplest way but you can use selection state of your view as this:

@Override
public void onClick(View v) {
         if(v.selected()){
             yearBar.setVisibility(View.GONE);
             yearBar.setTag("off");
             Toast.makeText(getActivity(),"Click detected!", Toast.LENGTH_LONG).show();
         }
         else{
              //do somthing else
         }
         v.setSelected(!v.isSelected());
}
Ad
source: stackoverflow.com
Ad