【发布时间】:2019-08-18 15:27:26
【问题描述】:
我正在尝试在单击按钮时更改 android:layout_marginStart 和 android:layout_marginEnd 以及 imageView,但我似乎所能做的就是在 px 中而不是 dp 中需要它。当活动加载时,我将它限制在另一个图像的左侧和右侧,另一个图像是 300dp 宽,我要移动的图像的边距设置为 150dp 和 150dp,我希望能够将它设置为任何东西,目前测试 30dp(开始)和 270dp(结束),所以它是从左边开始的 10%。
XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<ImageView
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/bar"
android:minHeight="50dp"
android:minWidth="300dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
android:backgroundTint="#00050505"/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
app:srcCompat="@drawable/ic_arrow_drop_up_black_24dp"
android:id="@+id/imageView4"
app:layout_constraintStart_toStartOf="@+id/bar"
app:layout_constraintEnd_toEndOf="@+id/bar"
android:layout_marginStart="150dp"
android:layout_marginEnd="150dp"
app:layout_constraintTop_toTopOf="@+id/bar"
app:layout_constraintBottom_toBottomOf="@+id/bar"
android:layout_marginTop="40dp"/>
<Button
android:text="Change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/bar"
android:layout_marginBottom="8dp"
android:onClick="changeValue" android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Kotlin 文件:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.result)
}
fun changeValue(view:View){
imageView4.updateLayoutParams<ConstraintLayout.LayoutParams> {
marginEnd = 270
marginStart = 30
}
}
像这样设置 marginEnd 和 marginStart 是要求像素而不是 dp,所以它对所有手机都不同,有没有办法将 150dp(开始)和 150dp(结束)更改为其他值?
谢谢
【问题讨论】:
标签: android android-studio kotlin imageview