android 如何更改ConstraintLayout中元素的layout_marginTop值?

afdcj2ne  于 2022-12-25  发布在  Android
关注(0)|答案(1)|浏览(180)

我有以下约束布局:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/my_text"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="@string/txt_string"

        app:layout_constraintBottom_toBottomOf="@id/one"
        app:layout_constraintEnd_toStartOf="@id/two"
        app:layout_constraintStart_toEndOf="@id/three"
        app:layout_constraintTop_toTopOf="@id/four"
        android:layout_marginTop="@dimen/margin_dim"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

我想要的是在代码中更改marginTop的值:
这是我所拥有的,但我还没有找到任何方法来设置顶部边距:

AppCompatTextView mytext;

private void onCreate(@Nullable Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        mytext = findViewById(R.id.my_text);

//here I would like to make something like :
// mytext.setTopMargin(Xdp);

}

suzh9iv8

suzh9iv81#

请尝试以下代码..

ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT);
        params.setMargins(0,10,0,0);
mytext.setLayoutParams(params);

setMargin表示以下坐标

setMargin(left,top,right,bottom);

相关问题