В моем приложении для Android я хочу создать группу из ConstraintLayouts
, в которой каждый имеет, например, ImageView
и TextView
.
Все создается из кода, кроме одного TableRow
с которого я начну.Моя проблема заключается в том, что, несмотря на возможность установки полей через LayoutParams для ConstraintLayout
, ImageView
и TextView
не меняются вообще, когда я пытаюсь установить поля.
public fun generateAsset(tableRow: TableRow) {
// <android.support.constraint.ConstraintLayout
// android:layout_margin="4dp"
// android:background="@drawable/x32_tile_dark">
val clayout = ConstraintLayout(context)
tableRow.addView(clayout)
val cparams = clayout.layoutParams as TableRow.LayoutParams
cparams.setMargins(4, 4, 4, 4) // <--- Works correctly!
clayout.layoutParams = cparams
clayout.setBackgroundResource(R.drawable.x32_tile_dark)
// <ImageView
// android:layout_width="0dp"
// android:layout_height="60dp"
// android:layout_marginTop="8dp"
// app:srcCompat="@drawable/x256_spaceship_door_gray_blue" />
val iView = ImageView(context)
clayout.addView(iView)
val iparams = iView.layoutParams as ConstraintLayout.LayoutParams
iparams.width = ConstraintLayout.LayoutParams.MATCH_PARENT
iparams.height = 200
iparams.setMargins(8, 8, 8, 8) // <--- Does not do anything!
iView.layoutParams = iparams
iView.setImageResource(R.drawable.x256_spaceship_door_gray_blue)
// <TextView
// android:text="Massive Spaceship Door"
// android:layout_marginLeft="8dp"
// android:layout_marginRight="8dp"
// android:layout_marginBottom="4dp"
// android:textColor="@android:color/white" />
val ntext = TextView(context)
clayout.addView(ntext)
val nparams = ntext.layoutParams as ConstraintLayout.LayoutParams
nparams.setMargins(8, 8, 8, 8) // <--- Does not do anything!
ntext.layoutParams = nparams
ntext.setTextColor(Color.WHITE)
ntext.text = assetName
}
Причина, по которой это не работает, вероятно, в том, что я не установил ограничения ImageView
и TextView
, но как мне это сделать в коде?
ImageView
должно быть правильнымв центре ConstraintLayout
, в то время как TextView
должен находиться в центре, но внизу.
Как я могу установить ограничения, чтобы сделать то, что я описал выше?