문제

Sorry for my English

May be the View.isInLayout() method does the same what I want, but it added in Android in API version 18, and I use MIN VERSION == 9 in my app.

What can I do?

At the moment I use the next code to catch the moment, when view will be placed on layout, i.e. to catch the moment, when view will have actual sizes:

public static void runOnViewPlacedOnLayout(final Runnable runnable) {
    ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    removeOnGlobalLayoutListener(view, this);
                    runnable.run();
                }
           }
    );
}


@SuppressWarnings("deprecation")
private static void removeOnGlobalLayoutListener(View view, ViewTreeObserver.OnGlobalLayoutListener listener) {
    ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
    if (viewTreeObserver == null) {
        return;
    }
    if (Build.VERSION.SDK_INT < 16) {
        viewTreeObserver.removeGlobalOnLayoutListener(listener);
    } else {
        viewTreeObserver.removeOnGlobalLayoutListener(listener);
    }
}

But in my code a view may be already placed on layout. In that case what can I do?

도움이 되었습니까?

해결책

To know if a view is added to a layout, you do

View view = layout.findViewById(int id);

or

View view = layout.findViewByTag(Object tag);

and ...

if(view != null) ... //view is already added

Depending on your requirements, you either then call layout.removeView(view) to remove the view and add a new, or update it or do nothing... or whatever you want :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top