Reputation: 3451
I'm teaching a few colleagues Java with the intent to go into Android game programming. Is there a way to display a box on the screen, and when you touch it it changes colors, without creating an Activity (this is in Eclipse) and diving into the ugly world of XML?
Upvotes: 6
Views: 4178
Reputation: 6620
I hear what you're saying, and yes - while I do agree that XML is boring when you just want to code games in android - i can say that XML is an neccessary evil of android. At least put ViewStubs in the XML and inflate them in the code later on.
Or get used to invoking many "new LayoutParams" calls if you want them formatted properly.
But your class really needs to overwrite Activity if you want it working on Android.
Upvotes: 2
Reputation: 1118
Here is an example for programmatically creating UI in Android as you requested
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button changeColor = new Button(this);
changeColor.setText("Color");
changeColor.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
changeColor.setOnClickListener(new View.OnClickListener() {
int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
@Override
public void onClick(View view) {
final Random random = new Random();
view.setBackgroundColor(colors[random.nextInt(colors.length - 1) + 1]);
}
});
setContentView(changeColor);
}
However, I strongly encourage using XML for your layouts. It is much easier and quicker to use XML once your understand it, so here is a tutorial for you.
Upvotes: 3
Reputation: 6380
You can create widgets programmatically and add them to an layout which you set as the content view in onCreate. Something along the lines of this would work:
RelativeLayout layout = new RelativeLayout(this);
Button btnChangeColour = new Button(this);
btnChangeColour.setText("Change Colour");
btnChangeColour.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.setBackgroundColor(...);
}
});
layout.addView(btnChangeColour);
setContentView(layout);
Upvotes: 2