Android - Заворачивать кнопки в поле зрения - PullRequest
0 голосов
/ 16 марта 2020

Я пытаюсь сделать обтекание кнопок в LinearLayout в Android, но они просто продолжают справа от вида (слово, показанное на скриншоте, должно быть "HELLO", поэтому я хочу "O" чтобы перейти к следующей строке).

enter image description here

Я добавляю кнопки программно, но даже если я кодирую их в файле макета 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);
    }

Любой совет будет оценен. Спасибо!

Ответы [ 2 ]

1 голос
/ 16 марта 2020

В итоге я использовал FlexboxLayout, который отлично подходит для этого. Спасибо тем, кто предложил предложения!

0 голосов
/ 16 марта 2020

Прежде всего, нет необходимости использовать ConstraintLayout , вы можете использовать LinearLayout в качестве родительского макета.

Затем с целью отображения всех Кнопки в одной строке, вы должны установить вес для LinearLayout в XML и установить вес для представлений, которые вы добавляете в него.

Файл 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>

И в коде вы должны установить вес для каждого просмотра, добавив , 1.0f к LayoutParam:

 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);
}
...