Check if view element is added to layout or not programmatically

前端 未结 7 675
予麋鹿
予麋鹿 2021-01-01 09:47

In my fragment class, I add a child view element programmatically to my layout conditionally :

LinearLayout child = (LinearLayout) inflater.inflate(R.layout.         


        
相关标签:
7条回答
  • 2021-01-01 10:14

    I think you can simply use

    findViewById(your_view_id) 
    

    method: If its result is null the view does not exists, otherwise the view is present

    0 讨论(0)
  • 2021-01-01 10:16

    With AndroidX you can use ViewGroup.contains(view: View): Boolean extension function.

    0 讨论(0)
  • 2021-01-01 10:17

    maybe you can try this

    child.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                child.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                // add to parent
            }
        });
    

    or this one

    child.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
    
            }
    
            @Override
            public void onViewDetachedFromWindow(View v) {
    
            }
        });
    
    0 讨论(0)
  • 2021-01-01 10:18

    Sorry for late reply but you may try this alternative:

    use container.getChildCount(); before adding and after adding a view. Like :

    int x = container.getChildCount();
    
    container.addView(child, params);
    
    int y = container.getChildCount();
    
    if(y > x)
       Toast.makeText(context, "View Successfully Added!", Toas.LENGTH_SHORT).show();
    
    0 讨论(0)
  • 2021-01-01 10:25

    Or if you have a view instance to find, you could:

    if (container.indexOfChild(childView) == -1) {
      // Add child to container.
    }
    
    0 讨论(0)
  • 2021-01-01 10:27

    I cannot write a comment so I write it here as a solution: From API level 19 you can call isAttachedToWindow() which doesn't help a lot, but if you are aiming API 19 or higher, then this should work by the documentation.

    0 讨论(0)
提交回复
热议问题