Constraint Layout中的视图在Java中更改宽度和高度时移动到顶部

时间:2018-06-18 13:51:23

标签: android android-constraintlayout

当我在java(Constraint Layout)中修改按钮的宽度和高度时,按钮会在点击时自动移动到顶部。请检查下面的代码,让我知道问题所在。 PS - 我是新约束布局

布局文件

LIKE

Java代码

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ImageButton
        android:id="@+id/ibEgg"
        android:layout_width="250dp"
        android:layout_height="350dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@null"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/egg" />

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:1)

您正在创建新的LayoutParams,因此您需要以编程方式设置约束,这是这样的:

ibEgg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(250, 350);
                    layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
                    ibEgg.setLayoutParams(layoutParams);
                    return true; // if you want to handle the touch event
                case MotionEvent.ACTION_UP:
                    ConstraintLayout.LayoutParams layoutParams1 = new ConstraintLayout.LayoutParams(300, 400);
                    layoutParams1.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams1.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams1.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams1.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
                    ibEgg.setLayoutParams(layoutParams1);
                    return true; // if you want to handle the touch event
            }
            return false;
        }
    });