Use android layout randomly

0

Well, I want to randomly call a layout, the problem is to call it, I thought about saving all the layouts in an array and based on randomly generated numbers call the layout in that position of the array, I thought I would do it this way:

    String listalayouts[] = new String[100];
    listalayouts[0]="layout1.xml";

    botao.setOnClickListener(new View.OnClickListener() {
        String x="R.layout."+listalayouts[0];
        public void onClick(View v) {
            setContentView(x);
        }
    });

This does not work because x is not of type View and you can not do cast from String to view. Does anyone have a solution?

Thank you in advance for any help.

    
asked by anonymous 08.11.2015 / 03:49

1 answer

0

You do not need to pass View to method setContentView() . This method also accepts a int as a parameter, this int is the id of the layout you want to use.

So what you can do is find the id for the layout you want to use and pass it as a parameter in the setContentView() method. In your case, you could do the following:

String listalayouts[] = new String[100];

listalayouts[0]="layout1"; // Não é necessário colocar a extensão ".xml"

botao.setOnClickListener(new View.OnClickListener() {

 // Pega o id do layout baseado no nome dele
 // o parametro "layout" no getIdentifier() deve ser mantido

 int resID = context.getResources().getIdentifier(listalayouts[0],"layout", context.getPackageName());

    public void onClick(View v) {
        setContentView(resId);
    }
});
    
08.11.2015 / 12:25