检测视图是否添加到布局中

Detect if a view is added to layout or not

我正在使用 OnLongClickListener 检测按钮是否显示在布局中。

目前我正在使用 button.getVisibility 来检测按钮在布局上的可见性,我将其设置为 button.setVisibility,但现在我想更改它以使用这些函数:

如何通过这种方式检测视图是否添加到布局中?

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;
}

到目前为止我的解决方案: (view.isLaidOut)

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

我担心的另一个问题是默认情况下按钮出现在列表的开头而不是结尾。只需在以下行中添加“, 0”即可解决此问题:

F3_layout.addView(button3F, 0);

这会将每个新创建的按钮都放在最顶部,但仍然不是我想要的。

跟进: 在开始添加和删除按钮之前,我仍然希望保留按钮的原始顺序;这将基本上复制列表,复制每个按钮,并按照与原件出现的相同顺序从顶部填充。

在此先感谢您的帮助。

您可以采用以下一种方法:

//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;
}