首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android -视图中的换行按钮

Android -视图中的换行按钮
EN

Stack Overflow用户
提问于 2020-03-16 23:14:45
回答 2查看 166关注 0票数 0

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

我以编程方式添加了这些按钮,但是即使我将它们编码到XML布局文件中,它们仍然不会包装。下面是包含LinearLayout容器的布局文件,我将在其中动态添加按钮:

代码语言:javascript
复制
<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>

下面是我用来创建和添加平铺按钮的代码:

代码语言:javascript
复制
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);
    }

任何建议都将不胜感激。谢谢!

EN

Stack Overflow用户

发布于 2020-03-16 23:31:53

首先,不需要使用您可以使用LinearLayout作为父布局的ConstraintLayout。

然后,为了在一行中显示所有按钮,您必须在XML中设置LinearLayout的权重,并为添加到其中的视图设置权重。

xml文件应如下所示:

代码语言:javascript
复制
<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来设置每个视图的权重:

代码语言:javascript
复制
 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);
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60708558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档