Подтвердить что ты не робот

Как программно добавлять кнопки в макет по одному в нескольких строках?

Как создать список кнопок один за другим в нескольких строках? Я сделал это:

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
    for (int i = 1; i < 10; i++) {
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button " + i);
        btnTag.setId(i);
        layout.addView(btnTag);
        ((Button) findViewById(i)).setOnClickListener(this);
    }

и получил только одну строку:

I got this
Как перейти к следующей строке программно?

4b9b3361

Ответ 1

Проблема заключается в том, что ваши кнопки не будут автоматически переноситься на следующую часть экрана. Вы должны конкретно сказать Android, как вы хотите, чтобы ваши представления были расположены. Вы делаете это, используя ViewGroups, такие как LinearLayout или RelativeLayout.

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

for (int i = 0; i < 3; i++) {
    LinearLayout row = new LinearLayout(this);
    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    for (int j = 0; j < 4; j++ {
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button " + (j + 1 + (i * 4));
        btnTag.setId(j + 1 + (i * 4));
        row.addView(btnTag);
    }

    layout.addView(row);
}

Я предполагаю, что R.id.linear_layout_tags является родительским LinearLayout вашего XML для этого действия.

В основном, что вы здесь делаете, вы создаете LinearLayout, который будет рядом с четырьмя кнопками. Затем добавляются кнопки и каждому присваивается число по возрастанию в качестве идентификатора. Когда все кнопки добавлены, строка добавляется в ваш макет активности. Затем он повторяется. Это всего лишь некоторый псевдокод, но он, вероятно, будет работать.

О, и в следующий раз обязательно потратьте больше времени на свой вопрос...

https://stackoverflow.com/questions/how-to-ask

Ответ 2

Это похоже на 1 ответ, но без необходимости делать XML файл.

public class mainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

        for (int i = 0; i < 3; i++) {
            LinearLayout row = new LinearLayout(this);
            row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

            for (int j = 0; j < 4; j++) {
                Button btnTag = new Button(this);
                btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                btnTag.setText("Button " + (j + 1 + (i * 4 )));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            layout.addView(row);
        }
        setContentView(layout);
        //setContentView(R.layout.main);
    }
} 

Ответ 3

Это поможет

private void addingParticipantinFrame() {
        TableRow row;
        final int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
        add_button_particiapants.setVisibility(View.VISIBLE);
        if (arrrItemSelcted != null && arrrItemSelcted.size() > 0) {

            arrrItemSelcted.remove(0);
            int i = 0;
            int j = 0;
            int width = (screenWidth - (arrrItemSelcted.size())*4)/arrrItemSelcted.size();

            while (i<arrrItemSelcted.size()) {
                j = i + 4;
                row = new TableRow(mParentActivity);
                TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
                row.setLayoutParams(lp);
                row.setWeightSum(4);
                while ((i<j)&&(i<arrrItemSelcted.size())) {
                    Button iBtn = new Button(mParentActivity);
                    iBtn.setGravity(Gravity.CENTER_HORIZONTAL);
                    iBtn.setMinimumWidth(100);//I set 100px for minimunWidth.
                    iBtn.setWidth(width);
                    iBtn.setText(Integer.toString(i + 1));
                    iBtn.setId(i + 1);
                    row.addView(iBtn, 4 + i - j);
                    i++;
                }
                add_button_particiapants.addView(row);
            }



            }
        }

Ответ 4

У меня возникла проблема, что количество просмотров, которые должны быть размещены в пользовательском интерфейсе, было задано во время выполнения. Поэтому я решил, что хочу только четыре вида в одной строке и соответствующим образом адаптировать код. Кроме того, я всегда заполнял последнюю строку невидимыми текстами редактирования, чтобы представления в последней строке также имели ту же ширину, что и представления в строке выше:

        // 1.0f is the weight!
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        layoutParams.setMarginEnd(10);

        for (int i = 0; i < Math.ceil(discipline.getSeries_count() / 4.0); i++) {
            LinearLayout layoutRow = new LinearLayout(MyActivity.this);
            layoutRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

            // add only four edit texts to row and move to next line afterwards
            for (int j = 0; j < 4; j++) {
                etSeries = new EditText(MyActivity.this);
                etSeries.setInputType(InputType.TYPE_CLASS_NUMBER);
                int iIndex = (j + 1 + (i * 4));
                etSeries.setText(getResources().getString(R.string.series) + " " + iIndex);
                etSeries.setId(iIndex);
                etSeries.setId(i);
                etSeries.setSelectAllOnFocus(true);
                etSeries.setLayoutParams(layoutParams);
                etSeries.setVisibility(iIndex > discipline.getSeries_count() ? View.INVISIBLE : View.VISIBLE);
                layoutRow.addView(etSeries);
            }
            layoutSeries.addView(layoutRow);
        }