I have to use an OnGlobalLayoutListener
object and then to remove the listener, I had a problem with deprecated methods that I resolve with following code.
protected void onCreate(Bundle savedInstanceState) {
final LinearLayout llTotal = (LinearLayout) findViewById(R.id.mmc_ll);
ViewTreeObserver vto = llTotal.getViewTreeObserver();
if(vto.isAlive()){
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//
// mycode
//
if (Build.VERSION.SDK_INT<16) {
removeLayoutListenerPre16(llTotal.getViewTreeObserver(),this);
} else {
removeLayoutListenerPost16(llTotal.getViewTreeObserver(), this);
}
}
});
}
super.onCreate(savedInstanceState);
}
@SuppressWarnings("deprecation")
private void removeLayoutListenerPre16(ViewTreeObserver observer, OnGlobalLayoutListener listener){
observer.removeGlobalOnLayoutListener(listener);
}
@TargetApi(16)
private void removeLayoutListenerPost16(ViewTreeObserver observer, OnGlobalLayoutListener listener){
observer.removeOnGlobalLayoutListener(listener);
}
Is it correct? There is a better way to handle compatibility?
Running the code in emulator with API 10 I have the following warning in LogCat
04-24 09:30:12.565: I/dalvikvm(471): Could not find method android.view.ViewTreeObserver.removeOnGlobalLayoutListener, referenced from method com.my.project.ActivityHome.removeLayoutListenerPost16
04-24 09:30:12.565: W/dalvikvm(471): VFY: unable to resolve virtual method 2950: Landroid/view/ViewTreeObserver;.removeOnGlobalLayoutListener (Landroid/view/ViewTreeObserver$OnGlobalLayoutListener;)V
Can I ignore them of I have to fix in some way?
Of course that check the Android version and call the correct method is much more prudent, but if you take a look on the Android source code you can see something interesting:
This code was snipped from API 18
According to the docs:
Works like a charm.
I'm using this in my project:
looks similar to yours. Tested on different devices (4.2.2 & 2.3.3) and it run perfectly. seems like it's the only way....If you find anything else I would like to know it. good luck
I think the correct way is using
Build.VERSION.SDK_INT
andBuild.VERSION_CODES
: