java - 检测 View 是否添加到布局中

标签 java android android-layout get visibility

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

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

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

  • button_layout.addView(按钮)
  • button_layout.removeView(按钮)

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

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

关于java - 检测 View 是否添加到布局中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57515960/

相关文章:

java - 如何从我的 Android 设备获取未读短信/未接来电?

java - 在哪里放置 AsyncTask() 以便我可以调用它来加载图像?

android - 错误的屏幕宽度和高度

java - 使用更严格的访问修饰符覆盖方法

java - Eclipse 与 IcedTea : use max memory

java - 词法分析器操作中不允许使用属性引用

java - Gradle任务sonarquube在http://localhost:9000/api/settings/values.protobuf上失败并显示401错误

android - 使用 Gradle 在 Android 中构建 JavaFX 应用程序

Android:GridLayout 的分隔线

android - AppBar 在滚动时隐藏 View 直到折叠