2016-08-19 52 views
0

我創建這些視圖>>>□口□如何在RelativeLayout中將視圖與無邊距的另一個視圖對齊?

<View 
    android:id="@+id/a" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:background="@color/opaque_red" /> 
<View 
    android:id="@+id/b" 
    android:layout_width="20dp" 
    android:layout_height="20dp" 
    android:layout_alignBottom="@id/a" 
    android:layout_toRightOf="@id/a" 
    android:background="@color/opaque_red" /> 
<View 
    android:id="@+id/c" 
    android:layout_width="20dp" 
    android:layout_height="20dp" 
    android:layout_alignBottom="@id/a" 
    android:layout_toLeftOf="@id/a" 
    android:background="@color/opaque_red" /> 

然後,我讓a可以在屏幕內移動

// v is whole screen 
a=v.findViewById(R.id.a); 

a.setOnTouchListener(new View.OnTouchListener() { 
    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) { 

     if (motionEvent.getAction() == MotionEvent.ACTION_MOVE || motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 

      int x = (int) motionEvent.getRawX(); 
      int y = (int) motionEvent.getRawY(); 

      RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) a.getLayoutParams(); 

      // calculate x y should set to a, int[0] is x, int[1] is y 
      int[] xy=centerPointToLeftTop(x,y,a.getMeasuredWidth(),a.getMeasuredHeight()); 

      // limit the a inside the screen. b and c just follow the a, they can go to outside of screen 
      if(xy[0]<0) { 
       params.leftMargin = 0; 
      } else if (xy[0] > v.getMeasuredWidth()- a.getMeasuredWidth()){ 
       params.leftMargin=v.getMeasuredWidth()-a.getMeasuredWidth(); 
      } else { 
       params.leftMargin = xy[0]; 
      } 
      a.setLayoutParams(params); 
      v.invalidate(); 
     } 

     return true; 
    } 
}); 

保證金是要改變的Android

的視圖位置的唯一途徑

但是邊距也會影響兩個視圖之間的對齊,所以c視圖(左方)不會跟着a視圖

如何對齊視圖無邊距?或者有沒有其他方式來移動視圖而不更改邊距?

回答

0

刪除

android:layout_alignBottom="@id/a" 
android:layout_toLeftOf="@id/a" 

從視圖C。因爲這些行會通知android,如果有移動,我們也需要移動c。因此刪除這些行並添加任何與視圖相關的屬性而不是元素a。

+0

如果我刪除了這些,我怎樣才能把'c'推到'a'的左邊,並且當我移動'a'時如何使它跟隨'a'? –

+0

你可以添加屏幕截圖或你的佈局。所以我們可以準確理解你的問題。 –

相關問題