如何改组XML布局

时间:2014-01-03 09:38:21

标签: android xml random-sample

我在Android中开发应用程序时非常新颖

当我点击Layout 时,如何随机更改当前活动Button?我真的不知道如何以及从哪里开始编码

public class RandomSample extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button random = (Button) findViewById(R.id.button1);

    random.setOnClickListener(new View.OnClickListener() {
    int [] layouts = {R.layout.layout1, R.layout.layout2, R.layout.layout3};
    Random r = new Random();

        @Override
        public void onClick(View v) {
            setContentView(r.nextInt(layouts.length));
        }
    });
}
}

这就是我的所作所为,但注意到它似乎在起作用

4 个答案:

答案 0 :(得分:1)

声明布局ID的数组,然后将其更改为setContentView()

int[] layouts={R.layout.l1, R.layout.l2, R.layout.l3, R.layout.l4};
Random r=new Random();

在特定按钮的onClick()方法

setContentView(r.nextInt(layouts.length));

答案 1 :(得分:1)

您发布的问题是您尝试将随机索引设置为内容视图而不是其关联的布局。我在下面修改了你的代码。

private static final int[] layouts = {R.layout.layout1, R.layout.layout2, R.layout.layout3};
Random r = new Random();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button random = (Button) findViewById(R.id.button1);
    random.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // This is just a number 0 - 2. It should not be set to content view.
            int index = r.nextInt(layouts.length);
            int nextLayout = layouts[index];
            setContentView(nextLayout);
        }
    });
}

答案 2 :(得分:1)

在您的活动中

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btn=(Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
                      setContentView(R.layout.second);
                      }
              });
        }

答案 3 :(得分:1)

映射在R类上的每个id都是一个整数。因此,您可以使用Random类中的nextInt()方法来选择随机布局。

尝试这样的事情:

int firstLayout = R.layout.l1; //your first layout
int numberOfLayouts = 5; // the number of layouts that you have

myButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        Random r = new Random();
        setContentView(r.nextInt(numberOfLayouts) + firstLayout);
    }
};