在 Android 布局文件中指定目标 API 级别?

9
我需要在布局中添加一个数字钟。我的最低支持的API级别是14。我发现API级别低于17有一个数字钟小部件(之后被弃用),而API 17及以上有一个文本时钟。
因此,我可以在xml中添加两个布局,并根据代码中的版本号动态设置可见性。但是xml将不断显示我已经使用了Text Clock,而我的最低支持级别是14。所以:
  1. Is there a way in the xml to specify to ignore the min-sdk error. Something like

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    

这是我们在普通Java代码中使用的。

  1. Is there a way in XML to specify to use a particular widget based on version number. Some kind of if else statement in the xml that says:

    if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        //Use text clock
    } else {
        // Use digital clock
    }
    

“Text Clock” 应该是完全向后兼容的... - Thomas Vos
1个回答

13

你可以使用工具目标API。

<item name="android:fontFamily" tools:targetApi="jelly_bean">sans-serif-light</item>

这也可以工作

<item name="android:fontFamily" tools:targetApi="17">sans-serif-light</item>

不明白为什么这个答案会得到这么多赞,“tools:targetApi” 不会起作用。要针对特定的 API,您必须像 @jlopez 在这里回答的那样创建不同的资源文件夹 https://stackoverflow.com/a/30434712/5636313。 - Farid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接