Question about arrays and buttons in eclipse + android java project
well im kind of new to eclipse anyways i was wondering is there a way for me to create an array of buttons in the java code 开发者_如何学Gorather then a xml file, then define there positions on the layout.
Every Button object is a view itself. Therefore, it can be added to a parent Layout (like the LinearLayout). The easiest way IMHO is creating the XML only for the things you know that will not change, or maybe using a TableLayout. Then, add the buttons.
LinearLayout mainLayout = findViewById(R.id.mainLayout);
Button[] btnArray = new Button[3];
for(Button button : btnArray){
button = new Button(/*Required params */);
// button.something , play with text and onclick and positions...
mainLayout.addView(button);
}
Is this what you're trying to do?
LinearLayout linear = (LinearLayout) findViewById(R.id.linear);
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
精彩评论