-8

I want to write my first android app using the Android Studio and getting some problems.

I want to write a quizapp and for each answer I want to add a button. But the count of the answers should not be the same for each answer. Thats why I want to add the buttons dynamically. I saw some sample code where the buttons are added via code.

Is there any way where I DONT have to add each button via code? I'm thinking about a way like in WPF where I have a list with answers in my viewmodel and my xaml is generating the buttons (e.g. ListView with ItemTemplate) automatically.

Thx to MattMatt for answering my question!

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51

2 Answers2

1

On the Android platform, a Button is a specific widget that is intended to perform a specific action when clicked. You describe a need for a dynamic number of buttons in a list format, for this you should use a RecyclerView, which would allow you to bind data to the number of clickable items.

If you want the appearance of each item in the RecyclerView list to look like a button, you can style the XML row item to look like one by inheriting the style from the built-in Button widget. This question asks how to style items with a background to provide Button-like visual states.

Community
  • 1
  • 1
MattMatt
  • 2,242
  • 33
  • 30
0
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);
}

http://www.mysamplecode.com/2011/10/android-programmatically-generate.html

Add button to a layout programmatically

How do I programmatically add buttons into layout one by one in several lines?

Community
  • 1
  • 1
nAkhmedov
  • 3,522
  • 4
  • 37
  • 72