简体   繁体   中英

How to align a view to another view without margin in RelativeLayout?

I created these views >>> □口□

<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" />

And then I make a can move within the screen

// 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;
    }
});

Margin is the only way to change position of view in Android

But the margin also affect the alignment between two views, so the c view (left square) will not follow a view

How to align the view without margin? or is there other way to move a view without changing the margin?

Remove

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

From the view c. because these lines will notify android that if a moves we need to move c also. So remove these lines and add any attributes which relates the view to the window not to the element a.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM