未考虑 TargetApi [英] TargetApi not taken into account

查看:19
本文介绍了未考虑 TargetApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的一种方法中,我们在列表视图中使用了 smoothScrolling.由于此方法在 API Level 8 (FROYO) 之前不可用,我们使用 TargetApi 注解来防止该方法在以前的 SDK 版本中被调用.

In one of our methods, we use smoothScrolling in a list view. As this method is not available before API Level 8 (FROYO), we used the TargetApi annotation to prevent the method from being called in previous SDK versions.

如您所见,我们确实在类定义和使用类对象的语句中使用 TargetApi 注释.这比需要的多.

As you can see, we do use TargetApi annotation both in class definition and in statements that use the objects of the class. This is more than needed.

我们的问题是 TargetApi 注释没有被考虑在内,导致我们的模拟器在 ECLAIR (SDK 7) 版本中崩溃.通过跟踪,我们才发现,应该只在 8+ 版本中执行的代码也在 7 版本中执行.

Our problem is that the TargetApi annotation is not taken into account and make our emulator crash in version ECLAIR (SDK 7). By tracing, we just realize that the code that should only be executed in versions 8+ is also executed in version 7.

我们是否遗漏了什么?

此代码在侦听器中:

@TargetApi(8)
private final class MyOnMenuExpandListener implements OnMenuExpandListener {
    @Override
    public void onMenuExpanded( int position ) {
        doScrollIfNeeded( position );
    }

    @Override
    public void onMenuCollapsed( int position ) {
        doScrollIfNeeded( position );
    }

    protected void doScrollIfNeeded( int position ) {
        if ( mListViewDocuments.getLastVisiblePosition() - 2 < position ) {
            mListViewDocuments.smoothScrollToPosition( position + 1 );
        }
    }
}

监听器是这样注册的:

@TargetApi(8)
private void allowSmothScrollIfSupported() {
    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO ) {
        //This if should not be necessary with annotation but it is not taken into account by emulator
        Log.d( LOG_TAG, "Smooth scroll support installed." );
        folderContentAdapter.setOnMenuExpandListener( new MyOnMenuExpandListener() );
    }
}

顺便说一句,我们在调试模式下运行代码,所以问题与混淆删除注释无关.

BTW, we run the code in debug mode, so the issue is not related to obfuscation removing annotations.

推荐答案

@TargetApi 不会阻止任何代码的运行,它只是为了注释代码和防止新 API 的编译器错误知道你只是有条件地打电话给他们.

@TargetApi does not prevent any code from being run, it is merely for annotating code and preventing compiler errors for new APIs once you know you are only conditionally calling them.

你仍然需要添加一些东西

You still need to add something along the lines of

if (Build.VERSION.SDK_INT > 7){
    //...
}

这篇关于未考虑 TargetApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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