2011-09-21 85 views
0

我有兩個AbsoluteLayout被稱爲Background_layoutForeground_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); 
    } 
    } 
    } 

任何建議,將不勝感激。

+2

您知道,有數百種不同類型的Android設備,AbsoluteLayout將無法工作? – Jack

+0

@Jack:真的嗎?那麼你的建議是什麼? –

+2

RelativeLayout,或除絕對之外的任何其他佈局。有了許多不同的屏幕尺寸,AbsoluteLayout可能在您的開發設備上運行良好,但是當我將它放在我的10.1英寸平板電腦上時,它可能不會。無論如何,我不是故意阻止你的原始問題,只是想讓你知道:)。 – Jack

回答

2

如果您從加速度計獲取值,則可以通過設置其佈局參數來更新視圖的位置。要將視圖移到左側,可以將該值設置爲左邊距。

LinearLayout.LayoutParams lp = LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT 
     ,LayoutParams.WRAP_CONTENT); 
lp.leftMargin = 10; 
view.setLayoutParameters(lp); 

這應該有效。

+1

謝謝,這是工作。 –