我正在使用Surfaceview编写一个游戏,有一个关于将数据保存到Bundle的问题。
最初,我有一个数组列表,它存储了只能上下移动的精灵的Y坐标(以整数的形式)。声明为:
static ArrayList<Integer> ycoordinates = new ArrayList<Integer>();
我使用以下方法将它们保存到捆绑包中:
myBundle.putIntegerArrayList("myycoordinates", ycoordinates);
并使用这个恢复它们:
ycoordinates.addAll(savedState.getIntegerArrayList("ycoordinates"));
这一切都很完美。然而,我不得不改变整个坐标系,所以它是基于德尔塔时间的,以允许我的精灵在不同的屏幕上以均匀的速度移动。这再次完美地发挥了作用。
然而,由于这个更改,我现在不得不将这些值存储为浮点值,而不是整数。
因此,我声明为:
static ArrayList<Float> ycoordinates = new ArrayList<Float>();
这就是背景,现在我的问题是,如何存储和恢复Float数组列表中的值?似乎没有"putFloatArrayList"或"getFloatAArrayList"。
(我使用了Arraylist而不是Array,因为精灵的数量需要是动态的)。
如有任何帮助,我们将不胜感激。
非常感谢
我写了几个简单的方法来在List和float[]之间转换。您可以在float[]上使用BundleputFloatArray()
和getFloatArray
。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args){
List<Float> in = new ArrayList<Float>();
in.add(3.0f);
in.add(1f);
in.add((float)Math.PI);
List<Float>out = toList(toArray(in));
System.out.println(out);
}
public static float[] toArray(List<Float> in){
float[] result = new float[in.size()];
for(int i=0; i<result.length; i++){
result[i] = in.get(i);
}
return result;
}
public static List<Float> toList(float[] in){
List<Float> result = new ArrayList<Float>(in.length);
for(float f : in){
result.add(f);
}
return result;
}
}