Use android layout randomly

Asked

Viewed 45 times

0

Good people, I intend to "call" a layout randomly, the problem is to call it, I thought to store all layouts in an array and based on the randomly generated numbers call the layout at that position of the array, I thought to do so:

    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 View type and can not cast String to view. Someone has a solution?

Thanks in advance for any help.

  • Switch between layouts with setContentView() is not a good idea, will bring many problems. Note that the method findViewById() is directly connected with the layout indicated with setContentView(). I suggest you use Fragments.

1 answer

0

You don’t need to pass a View pro method setContentView(). This method also accepts a int as a parameter, this being int is the id the layout you want to use.

So what you can do is find the id corresponding to the layout you want to use and pass it as parameter in the method setContentView(). 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);
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.