且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编写向后兼容的 Android 代码

更新时间:2023-02-07 20:28:27

内联 Api 错误是 ADT 的新内容,Eclipse 运行 Lint(我猜可能还有其他东西)来分析您的代码并将这些错误/警告内联.当您有关于优化或***实践的警告或提示时,这同样适用于 xml 布局.您可以使用注解来抑制类或特定方法中的这些错误.

Inline Api errors are new to ADT, Eclipse run Lint (and I guess something else maybe) to analyze your code and put those errors / warnings inline. The same apply to xml layout when you have warnings or hints about optimizations or best practices. You can use Annotations to suppress those errors in the class or in a particular method.

@TargetApi(16)
@SuppressLint("NewApi")

@TargetApi(16)
@SuppressLint("NewApi")

您放在这里的示例代码有问题,除了 API 级别检查之外,您在代码中还有一个 Advanceable 实例,该实例在 API 中不起作用 <16,因此检查 API 级别仅在调用新方法时有用,但不能在 IF 块之外引用新的 API 类.

There is a problem in the sample code you put here, beside the API level check you have an instance of Advanceable in the code that will not work in API < 16, so checking API level is only useful when you call new methods but you cant reference new API classes outside the IF block.

我认为可以接受的一种方法是创建一个抽象类和两个实现,然后实例化正确的实现,您可以使用带有静态方法的工厂类.

One approach I found acceptable is to create an abstract class and two implementations, then to instantiate the correct implementation you can use a factory class with static methods.

例如,要创建一个在内部使用一些新 API 类和方法的视图,您需要:

For example to create a view that use some new API classes and methods internally you need:

1 - 创建抽象类:

public abstract class CustomView {
    public abstract void doSomething();
}

  • 与所有 API 兼容的通用实现
  • 在此处定义抽象方法以拆分实现
  • 2 - 旧版实施

public class CustomLegacyView extends CustomView {
    public void doSomething(){
        //implement api < 16
    }
}

  • 实现 API 的抽象方法
  • 16
  • 3 - API 16 实现

    3 - API 16 implementation

@TargetApi(16)
public class CustomL16View extends CustomView {

    Advanceable myAdvanceable;

    public void doSomething(){
        //implement api >= 16
    }
}

  • 使用注解@TargetApi(16)
  • 实现 API >= 16 的抽象方法
  • 您可以在此处引用级别 16 的类(但不能在 CustomView 中)
  • 4 - 工厂类

public class ViewFactory {

    public static CustomView getCustomView(Context context) {

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return new CustomL16View(context);
        }else{
            return new CustomLegacyView(context);
        }

    }
}