Check if view element is added to layout or not pr

2019-02-11 11:13发布

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

LinearLayout child = (LinearLayout) inflater.inflate(R.layout.child_view, null);

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,100);

container.addView(child, params);

Since the above code will be run conditionally, so, at some point, I would like to check if the child view has added or not, how to make this checking programmatically?

6条回答
小情绪 Triste *
2楼-- · 2019-02-11 11:33

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

        }
    });
查看更多
小情绪 Triste *
3楼-- · 2019-02-11 11:36

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

查看更多
可以哭但决不认输i
4楼-- · 2019-02-11 11:38

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();
查看更多
在下西门庆
5楼-- · 2019-02-11 11:44

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

if (container.indexOfChild(childView) == -1) {
  // Add child to container.
}
查看更多
小情绪 Triste *
6楼-- · 2019-02-11 11:49

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.

查看更多
聊天终结者
7楼-- · 2019-02-11 12:00

If you creating view via inflater, you can check his parent

if(view.getParent() != null) {...}
查看更多
登录 后发表回答