A simple Android application without XML

I teach several Java colleagues with the intention of moving to Android programming. Is there a way to display a window on the screen, and when you touch it, it changes colors without creating an Activity (this is in Eclipse) and plunging into the ugly world of XML?

+5
source share
3 answers

Here is an example of programmatically creating a user interface on Android for your request

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 highly recommend using XML for your layouts. It’s much easier and faster to use XML as soon as you understand it, so here is a tutorial for you.

+3
source

, onCreate. - :

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);
+1

I heard what you say, and yes, although I agree that XML is boring when you just want to code games in android - I can say that XML is a necessary evil for Android. At least put ViewStubs in XML and inflate them in code later.

Or get used to calling many new LayoutParams calls if you want to format them correctly.

But your class really needs to rewrite Activity if you want it to work on Android.

+1
source

All Articles