android – 如何动态添加视图已经在xml布局中声明的RelativeLayout?

我在xml布局文件中声明了一个RelativeLayout.现在我想将视图从代码添加到现有的布局.我通过代码动态地添加了一个Button到这个现有的布局:

rLayout = (RelativeLayout)findViewById(R.id.rlayout); 
        LayoutParams lprams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        Button tv1 = new Button(this); 
        tv1.setText("Hello"); 
        tv1.setLayoutParams(lprams); 
        tv1.setId(1); 
        rLayout.addView(tv1); 

现在我需要在已经添加的按钮的右侧添加另一个按钮.我无法找到我可以在之前添加的按钮的右侧添加新的方式.

最佳答案
为第二个添加的Button LayoutParams添加规则RelativeLayout.RIGHT_OF:

    // first Button
    RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.rlayout);
    RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    Button tv1 = new Button(this);
    tv1.setText("Hello");
    tv1.setLayoutParams(lprams);
    tv1.setId(1);
    rLayout.addView(tv1);

    // second Button
    RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    Button tv2 = new Button(this);
    tv1.setText("Hello2");
    newParams.addRule(RelativeLayout.RIGHT_OF, 1);
    tv2.setLayoutParams(newParams);
    tv2.setId(2);
    rLayout.addView(tv2);

转载注明原文:android – 如何动态添加视图已经在xml布局中声明的RelativeLayout? - 代码日志