解决方案 »

  1.   

    你要获取到xml中RelativeLayout的id,在Relativelayout的基础上addView代码:protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_test);
    // 装载要填充的布局文件
    RelativeLayout rl = (RelativeLayout)findViewById(R.id.rl);
      
     
    Button btn=new Button(this);
    btn.setText("haha");

    // 创建新的LayoutParam对象
    RelativeLayout.LayoutParams rlp=new       RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT);
    rlp.addRule(RelativeLayout.BELOW,R.id.btn1);
    rlp.addRule(RelativeLayout.RIGHT_OF,R.id.btn1);
    // 这里的相对位置设置不起作用!为何?
    btn.setLayoutParams(rlp); 
    if(rl != null)
        rl.addView(btn);
    //addContentView(btn, rlp); }xml布局
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/rl"
            >
            <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"          
                android:text="1"
                android:id="@+id/btn1"
                ></Button>
        </RelativeLayout>
      

  2.   

    // 装载要填充的布局文件
    RelativeLayout rl=(RelativeLayout)getLayoutInflater().inflate(R.layout.activity_test, null);为什么这里没起作用啊?