【问题标题】:Detect if a view is added to layout or not检测视图是否添加到布局中
【发布时间】:2019-12-22 06:23:24
【问题描述】:

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

  • 如果按钮不在布局中,则必须添加
  • 如果按钮已经存在于布局中,则必须将其移除

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

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

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

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

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

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

提前感谢您的帮助。

【问题讨论】:

  • 你试过我的解决方案了吗?

标签: java android android-layout get visibility


【解决方案1】:

这是您可以采取的一种方法:

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

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多