Detect if a view is added to layout or not

dewie :

I'm using an OnLongClickListener to detect whether or not a button is being displayed in a layout or not.

  • if the button is not in the layout, it must be added
  • if the button is already present in the layout, it must be removed

Currently I'm using button.getVisibility to detect a button's visibility on the layout and I set it with button.setVisibility, but now I want to change it to work with these functions:

  • button_layout.addView(button)
  • button_layout.removeView(button)

How can I detect if a view is added to the layout or not in this way?

if (button.getVisibility() == View.GONE) {      // get button_layout view added/removed?
    button.setVisibility(View.VISIBLE);         // i don't want to use this
    button_layout.addView(button);              // only this
    return true;
} else if (button.getVisibility() == View.VISIBLE) {   
    button.setVisibility(View.GONE);
    button_layout.removeView(button);                       
    return true;
} else {
    return false;
}

MY SOLUTION THUS FAR: (view.isLaidOut)

if (button.isLaidOut()) {
    button_layout.removeView(button);
    return true;
} else {
    button_layout.addView(button);
    return true;
}

Another one of my concerns were having the buttons appear at the start of the list in stead of the end by default. This was fixed by simply adding ", 0" in the following line:

F3_layout.addView(button3F, 0);

This places every newly created button at the very top, but still isn't exactly what I want.

FOLLOW-UP: I would still like to preserve the original order of the buttons before they start getting added and removed; this will basically duplicate the list, copying each button, and filling from the top in the same order as the originals appeared.

Thanks in advance for any help.

a_local_nobody :

Here's one approach you can take:

//your specific ROOT layout : linear, relative, constraint etc which is to contain this button
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);

public boolean doesButtonExist (LinearLayout layout) {
    for (int i = 0; i < layout.getChildCount(); i++) {
        View view = layout.getChildAt(i);
        if (view instanceof Button) {
            //here, you can check the id of the view
            //you can call: view.getId() and check if this is the id of the button you want
            //you can also change the properties of this button here, if you DO find it
            //do something like return true
        }
    }
    return false;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161806&siteId=1