OnGlobalLayoutListener:德precation和兼容性 [英] OnGlobalLayoutListener: deprecation and compatibility

查看:369
本文介绍了OnGlobalLayoutListener:德precation和兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用 OnGlobalLayoutListener 对象,然后删除监听器,我曾与德precated方法有问题,我解决与以下code

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?

使用API​​ 10运行code在模拟器我在LogCat中以下警告

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?

推荐答案

我在我的项目中使用这样的:

I'm using this in my project:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
    if (Build.VERSION.SDK_INT < 16) {
        v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
    } else {
        v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
    }
}

看起来类似你的。 测试在不同的设备(4.2.2&安培; 2.3.3),并且完美运行。 好像它是唯一的方法....如果你发现任何东西,我想知道这一点。 好运气

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

这篇关于OnGlobalLayoutListener:德precation和兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆