如何通过加速度传感器移动我的布局?
问题描述:
我有两个AbsoluteLayout
被称为Background_layout
和Foreground_layout
在一个基地的XML。如何通过加速度传感器移动我的布局?
我想通过加速度计传感器移动第一个布局(Background_layout
)方向Y X Z,我该怎么做?
在这里你可以看到我的XML:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background_layout"
android:background="@drawable/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<AbsoluteLayout
android:id="@+id/foreground_layout"
android:layout_height="wrap_content"
android:background="@drawable/foreground"
android:layout_width="wrap_content"
android:layout_x="0dip"
android:layout_y="0dip">
</AbsoluteLayout>
</AbsoluteLayout>
我对方向的所有值,但我不知道我怎样才能在布局视图中使用它们。
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
float ValuX = (float) values[0];
float ValuY = (float) values[1];
float ValuZ = (float) values[2];
int ResValuX = new Integer(Float.toString(ValuX));
int ResValuY = new Integer(Float.toString(ValuY));
int ResValuZ = new Integer(Float.toString(ValuZ));
Background.addView(Background,ResValuX);
Background.addView(Background,ResValuY);
Background.addView(Background,ResValuZ);
}
}
}
任何建议,将不胜感激。
答
如果您从加速度计获取值,则可以通过设置其布局参数来更新视图的位置。要将视图移到左侧,可以将该值设置为左边距。
LinearLayout.LayoutParams lp = LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT
,LayoutParams.WRAP_CONTENT);
lp.leftMargin = 10;
view.setLayoutParameters(lp);
这应该有效。
+1
谢谢,这是工作。 –
您知道,有数百种不同类型的Android设备,AbsoluteLayout将无法工作? – Jack
@Jack:真的吗?那么你的建议是什么? –
RelativeLayout,或除绝对之外的任何其他布局。有了许多不同的屏幕尺寸,AbsoluteLayout可能在您的开发设备上运行良好,但是当我将它放在我的10.1英寸平板电脑上时,它可能不会。无论如何,我不是故意阻止你的原始问题,只是想让你知道:)。 – Jack