在Android中,我试图让按钮包裹在LinearLayout中,但它们只是继续显示在视图的右侧(屏幕截图中显示的单词应该是"HELLO",所以我希望"O“下拉到下一行)。

我以编程方式添加了这些按钮,但是即使我将它们编码到XML布局文件中,它们仍然不会包装。下面是包含LinearLayout容器的布局文件,我将在其中动态添加按钮:
<androidx.constraintlayout.widget.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"
app:layout_constrainedWidth="true"
tools:context=".LetterTileView">
<LinearLayout
android:id="@+id/TilesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constrainedWidth="true"
android:orientation="horizontal">
</LinearLayout>下面是我用来创建和添加平铺按钮的代码:
Context context = this;
LinearLayout layout = (LinearLayout) findViewById(R.id.TilesContainer);
LayoutParams params = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
params.setMargins(50, 50, 0, 0);
for (int i=0;i<wordLength;i++) {
Button tileButton = new Button(this);
tileButton.setLayoutParams(params);
tileButton.setText(wordStringtoLetters[i]);
tileButton.setId(i);
tileButton.setBackgroundResource(R.drawable.tile_button);
tileButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 36);
layout.addView(tileButton);
}任何建议都将不胜感激。谢谢!
发布于 2020-03-16 23:31:53
首先,不需要使用您可以使用LinearLayout作为父布局的ConstraintLayout。
然后,为了在一行中显示所有按钮,您必须在XML中设置LinearLayout的权重,并为添加到其中的视图设置权重。
xml文件应如下所示:
<LinearLayout
android:id="@+id/TilesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="5"
app:layout_constrainedWidth="true"
android:orientation="horizontal">
</LinearLayout>在代码中,您应该通过向LayoutParam添加,1.0f来设置每个视图的权重:
Context context = this;
LinearLayout layout = (LinearLayout) findViewById(R.id.TilesContainer);
LayoutParams params = new LayoutParams( LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,1.0f );
params.setMargins(50, 50, 0, 0);
for (int i=0;i<wordLength;i++) {
Button tileButton = new Button(this);
tileButton.setLayoutParams(params);
tileButton.setText(wordStringtoLetters[i]);
tileButton.setId(i);
tileButton.setBackgroundResource(R.drawable.tile_button);
tileButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 36);
layout.addView(tileButton);
}https://stackoverflow.com/questions/60708558
复制相似问题