这个是再写项目过程中遇到的低版本与新版本的一些方法兼容性问题,记录如下:
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.view.View;
import android.widget.TextView;
/**
* Created by LY on 2015/6/12.
* 兼容旧版&新版中的方法
*/
public class CompatUtils {
/**
* Sets background.
*
* @param view the view
* @param drawable the drawable
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void setBackground(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < 16) {
//noinspection deprecation
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
/**
* Sets text appearance.
*
* @param view the view
* @param appearanceRes the appearance res
*/
@TargetApi(Build.VERSION_CODES.M)
public static void setTextAppearance(TextView view, @StyleRes int appearanceRes) {
if (Build.VERSION.SDK_INT < 23) {
//noinspection deprecation
view.setTextAppearance(view.getContext(), appearanceRes);
} else {
view.setTextAppearance(appearanceRes);
}
}
/**
* Gets drawable.
*
* @param context the context
* @param drawableRes the drawable res
* @return the drawable
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Drawable getDrawable(Context context, @DrawableRes int drawableRes) {
if (Build.VERSION.SDK_INT < 21) {
//noinspection deprecation
return context.getResources().getDrawable(drawableRes);
} else {
return context.getDrawable(drawableRes);
}
}
/**
* Gets string.
*
* @param context the context
* @param stringRes the string res
* @return the string
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static String getString(Context context, @StringRes int stringRes) {
if (Build.VERSION.SDK_INT < 21) {
//noinspection deprecation
return context.getResources().getString(stringRes);
} else {
return context.getString(stringRes);
}
}
/**
* Gets color.
*
* @param context the context
* @param colorRes the color res
* @return the color
*/
@ColorInt
public static int getColor(Context context, @ColorRes int colorRes) {
if (Build.VERSION.SDK_INT < 21) {
//noinspection deprecation
return context.getResources().getColor(colorRes);
} else {
return context.getResources().getColor(colorRes, null);
}
}
}

本文提供了一系列实用的兼容性解决方案,旨在解决Android应用在不同API级别设备上运行时遇到的方法调用问题。通过条件判断,智能选择适配当前设备版本的API调用方式,确保了应用在低版本和新版本设备上的稳定性和用户体验。
1万+

被折叠的 条评论
为什么被折叠?



