2016-08-19 68 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

你可以添加屏幕截图或你的布局。所以我们可以准确理解你的问题。 –

相关问题