1

I'd like to be able to loop through a list of xml layout files instead of having to specify a particular one in the setContentView argument.

Obviously the types are incorrect, but something like:

ArrayList<String> pages = new ArrayList<String>();
//(Where each of the xml pages are stored like R.layout.page1, R.layout.page2, etc)
setContentView(pages.get(0));

Is this possible somehow?

litterbugkid
  • 3,534
  • 7
  • 36
  • 54
  • 1
    What visual effect do you want to achieve? – Sergii Rudchenko Nov 23 '11 at 20:51
  • @Sergey Rudchenko I just need to be able to load as many xml layout files as needed and loop through them to display without writing seperate activity classes for each of them. – litterbugkid Nov 23 '11 at 20:55
  • This is probably some kind of a reusable activity class. But still unclear what is the aim. – Vit Khudenko Nov 23 '11 at 20:56
  • Is this a kind of wizard? Are the page IDs really come to you as resource names (strings) in the runtime? – Sergii Rudchenko Nov 23 '11 at 20:59
  • @Arhimed Yes you are right, it is meant to be a reusable activity class. I wouldnt like to divulge the aim though. Hopefully this doesn't limit how much you can help me! – litterbugkid Nov 23 '11 at 21:00
  • @Sergey Rudchenko No they don't come as strings. They will always be called page1, page2, etc. I may just preload the Arraylist and do a catch block to carry on loading the activities until it cant find them anymore, but this seems quite redundant. – litterbugkid Nov 23 '11 at 21:02

3 Answers3

3

You should use the ViewFlipper widget instead. Here is an example.

It is cleaner to manage the content views and their children widgets this way.

Anyway, the resource IDs can be obtained from names using the Resources.getIdentifier method.

Sergii Rudchenko
  • 5,170
  • 2
  • 28
  • 24
  • This is great thank you, does exactly what I needed. It also allows me to go backwards and forwards between views very easily! – litterbugkid Nov 24 '11 at 16:11
2

Yes. it's possible. But two notes:

  1. The ids are ints, not Strings.
  2. You need to manage the views inside them properly.
MByD
  • 135,866
  • 28
  • 264
  • 277
2

In an application I have created I use the following code to set the image button to a particular resource:

imgBtnCard.setImageResource(this.getResources()
    .getIdentifier("com.twp.cptshitface:drawable/" +
        cardType + cardDetails[1] , null, null));

I would say that this is what you are looking for:

int resLayoutId = this.getResources().
    getIdentifier("your.package.namespace:layout/" +
    pages.get(0), null, null);

setContentView(resLayoutId);
// where pages.get(0) returns a string such as "main2"

I've quickly tested this code in the onCreateMethod.

remember to clean your project if you add more layouts and/or resources so the id's are updated!

TerryProbert
  • 1,124
  • 2
  • 10
  • 28