
在android自定义视图中保存状态时,直接将`drawable`对象序列化到`parcelable`中是不可行的,因为`drawable`及其子类通常不实现`parcelable`接口,会导致`classcastexception`。正确的做法是保存`drawable`的资源id,并在状态恢复时通过该id重新加载`drawable`,从而确保视图状态的正确恢复和应用的稳定性。
在Android开发中,自定义视图(Custom View)是实现独特UI和交互的关键。为了确保应用在配置变更(如屏幕旋转)或进程被系统回收后能恢复到之前的状态,我们需要在自定义视图中实现状态的保存与恢复机制。这通常通过重写onSaveInstanceState()和onRestoreInstanceState()方法,并结合Parcelable接口来实现。然而,当自定义视图内部包含Drawable对象时,直接将其作为Parcelable的一部分进行序列化,往往会遇到问题。
Drawable是Android图形绘制的基础抽象类,它定义了可绘制对象的基本行为。其具体实现类如VectorDrawable、BitmapDrawable等,虽然用途广泛,但它们通常不直接实现Parcelable接口。Parcelable接口是Android特有的一种高效序列化机制,要求对象能够将其自身内容写入Parcel(包裹),并能从Parcel中重建。
当尝试将一个非Parcelable的Drawable对象(例如VectorDrawable)写入Parcel时,Java运行时会尝试将其向上转型为Parcelable。如果转型失败,就会抛出java.lang.ClassCastException,提示“android.graphics.drawable.VectorDrawable cannot be cast to android.os.Parcelable”。即使尝试将其转换为Bitmap并再包装成BitmapDrawable,也可能因为BitmapDrawable仍然是一个Drawable的子类,而其内部的Bitmap可能才是Parcelable的,导致转换逻辑复杂且容易出错。
以下是一个典型的错误尝试,直接在自定义视图的SavedState中保存Drawable对象:
public class MyCustomView extends View {
private Drawable picture;
private Float degree = 0f;
// ... 构造函数和绘制逻辑 ...
private static class SavedState extends BaseSavedState {
// 错误:直接存储Drawable对象
Drawable picture;
Float degree = 0f;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
degree = source.readFloat();
// 错误:尝试将非Parcelable的Drawable读出
// 这会导致 ClassCastException
picture = source.readParcelable(getClass().getClassLoader());
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeFloat(degree);
// 错误:尝试将非Parcelable的Drawable写入
out.writeParcelable((Parcelable) picture, flags); // 这里会抛出 ClassCastException
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState myState = new SavedState(superState);
myState.degree = this.degree;
myState.picture = this.picture; // 将Drawable对象赋值给SavedState
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
this.degree = savedState.degree;
this.picture = savedState.picture; // 恢复Drawable对象
invalidate();
}
}当运行此代码并触发状态保存(例如旋转屏幕)时,应用会崩溃并抛出java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.os.Parcelable。
解决Drawable对象无法直接序列化问题的最佳实践是:不保存Drawable对象本身,而是保存其在资源文件中的唯一标识符——资源ID(int类型)。在需要恢复状态时,通过这个资源ID重新从资源管理器中加载Drawable。
这种方法的优势在于:
我们将修改SavedState类,用一个int类型的drawableResId来替代Drawable picture。
修改SavedState类:
修改onSaveInstanceState()方法:
修改onRestoreInstanceState()方法:
以下是修改后的代码示例:
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi; // 如果使用API 21+的getDrawable方法
public class MyCustomView extends View {
private Drawable picture;
private int pictureResId; // 用于保存Drawable的资源ID
private Float degree = 0f;
public MyCustomView(Context context) {
super(context);
init();
}
public MyCustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 示例:初始化一个Drawable,并记录其资源ID
// 假设您的Drawable是从R.drawable.my_vector_image加载的
// 在实际应用中,您可能通过属性设置或在代码中动态设置
this.pictureResId = R.drawable.my_vector_image; // 假设您的资源ID
this.picture = getContext().getDrawable(pictureResId);
// ... 其他初始化逻辑
}
// 设置Drawable的方法,同时更新资源ID
public void setPicture(int resId) {
this.pictureResId = resId;
this.picture = getContext().getDrawable(resId);
invalidate();
}
// ... 绘制逻辑 (使用this.picture进行绘制) ...
private static class SavedState extends BaseSavedState {
int drawableResId; // 保存Drawable的资源ID
Float degree = 0f;
public SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
degree = source.readFloat();
drawableResId = source.readInt(); // 读取资源ID
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeFloat(degree);
out.writeInt(drawableResId); // 写入资源ID
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState myState = new SavedState(superState);
myState.degree = this.degree;
myState.drawableResId = this.pictureResId; // 保存Drawable的资源ID
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
this.degree = savedState.degree;
// 恢复Drawable对象:根据资源ID重新加载
if (savedState.drawableResId != 0) { // 确保资源ID有效
this.pictureResId = savedState.drawableResId;
// 推荐使用带Theme的getDrawable方法,尤其是在API 21+
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
this.picture = getContext().getDrawable(this.pictureResId, getContext().getTheme());
} else {
this.picture = getContext().getResources().getDrawable(this.pictureResId);
}
}
invalidate(); // 重新绘制视图
}
}注意: 上述代码中的R.drawable.my_vector_image是一个占位符,您需要替换为实际的Drawable资源ID。在实际项目中,pictureResId的值通常会在视图初始化或通过属性设置时被赋值。
资源管理与效率: 通过资源ID重新加载Drawable是最高效的方式。Android系统会缓存这些资源,减少内存开销。避免尝试将复杂的Drawable对象转换为Bitmap再序列化,这不仅效率低下,还可能导致内存溢出,并且可能丢失VectorDrawable的矢量特性。
获取Context: 在onRestoreInstanceState()方法中,你需要一个Context来调用getDrawable()方法。自定义视图本身就是一个Context的子类(View的getContext()方法返回Context),所以可以直接使用this.getContext()。
主题兼容性: 从API 21 (Lollipop) 开始,Context.getDrawable(int id, Resources.Theme theme)方法允许你根据当前应用的主题加载Drawable,确保Drawable在不同主题下正确渲染。在onRestoreInstanceState中,推荐使用此方法:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
this.picture = getContext().getDrawable(this.pictureResId, getContext().getTheme());
} else {
// 对于旧版本API,使用过时的方法
this.picture = getContext().getResources().getDrawable(this.pictureResId);
}非资源Drawable的处理: 如果你的Drawable不是从资源文件加载的,而是通过代码动态生成的(例如,ShapeDrawable或GradientDrawable),那么保存资源ID的方法就不适用了。在这种情况下,你需要:
在Android自定义视图中处理Drawable对象的状态保存时,核心原则是避免直接序列化Drawable对象本身。由于Drawable及其许多子类不实现Parcelable接口,直接尝试序列化会导致运行时错误。最健壮和推荐的方法是保存Drawable的资源ID,并在视图状态恢复时,利用该资源ID从应用资源中重新加载Drawable。这种方法不仅解决了序列化问题,还充分利用了Android的资源管理机制,提高了应用的稳定性和效率。对于非资源Drawable,则需要根据其生成方式,考虑序列化其关键属性或重新生成。
以上就是Android自定义视图状态保存:避免直接序列化Drawable对象的策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号