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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With