views:

87

answers:

1

So I have made a little piece of code that will insert and manipulate a few images. Now my main problem is that this is very ugly and long, I was wondering if anything could be done to make it prettier.

    RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.board);

    ImageView i = new ImageView(this);
    i.setImageResource(R.drawable.blue_1);
    i.setId(400);

    ImageView j = new ImageView(this);
    j.setImageResource(R.drawable.red_1);
    j.setId(401);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(40,62);
    params.addRule(mRelativeLayout.ALIGN_PARENT_BOTTOM);
    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(40,62);
    params1.addRule(mRelativeLayout.ALIGN_PARENT_BOTTOM);
    params1.addRule(mRelativeLayout.RIGHT_OF, 400);    

    mRelativeLayout.addView(i, params);
    mRelativeLayout.addView(j, params1);
    setContentView(mRelativeLayout);

For example I have tried with just one layoutparams, but it seem to affect both pictures even if I make changes to it after the first picture is added.

Also I have a function that can return a string such as blue_1 o red_1 as a string to help me print my images, but it wont allow me to put strings into the i.setImageResource to get the picture :(

What can i do?

+2  A: 

The best way to tidy your code up would be to get rid of almost all of it and just define your layout in an XML file. That way you can just call setContentView(R.layout.my_layout_name) instead of manually creating the widgets and layout params yourself. If you're not too familiar with declaring layouts in XML, have a look at the dev docs. Alternatively, if you need to instantiate different parts of the UI separately, you can inflate the layout with a LayoutInflater.

For the second question, the Resources class has a getIdentifier method. You can do something like this:

getResources().getIdentifier("blue_1", "drawable", "com.my.package.here")

That'll return the resource ID, which you can then use instead of R.drawable.blue_1.

Chris Smith
ah awesome with the last part was what I was looking for :) Ill look into the inflater as well :)
Android Noob
also this helped me out a bit :) getResources().getIdentifier("blue_1", "drawable", getPackageName());
Android Noob