Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Android App Without XML

Tags:

java

android

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?

like image 369
Lincoln Bergeson Avatar asked Jul 29 '12 02:07

Lincoln Bergeson


2 Answers

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.

like image 53
almalkawi Avatar answered Oct 17 '22 00:10

almalkawi


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);
like image 31
jimmithy Avatar answered Oct 16 '22 22:10

jimmithy