Reputation: 25
I wrote a simple app in which I want to add some buttons programmatically. The problem is that it is not sure how many buttons have to be added. I tried to put the "Button button = new Button" into a for-loop, because I thougt it only creates a local variable. I guess that's my fault ;)
This is my code:
public class MainActivity extends Activity {
LinearLayout auswahl;
String element [] = new String [10]; //This is just an example, it would take many pages to show how this array gets created.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auswahl = (LinearLayout)findViewById(R.id.LinearLayout2);
element [1] = "A";
element [2] = "B";
element [3] = "C";
element [4] = "D";
element [5] = "E";
element [6] = "F";
element [7] = "G";
element [8] = "H";
element [9] = "I";
element [0] = "J";
int anzahl = element.length;
for (int i = 0; i <= anzahl; i++){
schreibeButtons(i, element[i]);
}
}
public void schreibeButtons(int i, String string){
Button button = new Button(this);
button.setText(sortiment);
button.setWidth(auswahl.getWidth());
button.setHeight(40);
button.setId(i*100);
auswahl.addView(button);
} }
Are there any questions on what I want to reach? How to reach my aim?
Upvotes: 0
Views: 644
Reputation: 20155
Mistake :
int anzahl = element.length;
Array of size n contains elements from 0 to n-1,
prasperK already pointed out that.
You are adding Every Button to your LinearLayout
auswahl
.
You can access your button from it only
Example : Number of Buttons - auswahl.getChildCount()
;
And you can access each button like this
To get button 1
Button button1=auswahl.getChildAt(0);
or simply by using ID
Button button1=(Button)auswahl.findViewById(101);
Upvotes: 1