Is there a way to set setContentView(int id) dynamically?

允我心安 提交于 2019-12-24 09:35:13

问题


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?


回答1:


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.




回答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.



回答3:


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!



来源:https://stackoverflow.com/questions/8248861/is-there-a-way-to-set-setcontentviewint-id-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!