【发布时间】:2012-08-31 07:52:41
【问题描述】:
在我们的一种方法中,我们在列表视图中使用了 smoothScrolling。由于该方法在 API Level 8 (FROYO) 之前不可用,因此我们使用 TargetApi 注解来防止在之前的 SDK 版本中调用该方法。
如您所见,我们确实在类定义和使用类对象的语句中都使用 TargetApi 注释。这比需要的多。
我们的问题是TargetApi注解没有被考虑在内,导致我们的模拟器在ECLAIR(SDK 7)版本中崩溃。通过追踪,我们才意识到,应该只在版本 8+ 中执行的代码,在版本 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() );
}
}
顺便说一句,我们在调试模式下运行代码,所以问题与混淆删除注释无关。
【问题讨论】:
-
顺便说一句,你可以写
@TargetApi(Build.VERSION_CODES.FROYO)而不是@TargetApi(8)。 -
你是对的。为此,您的 targetSDK 必须尽可能高。
标签: android annotations emulation