动态地向RelativeLayout添加内容

whe*_*ies 4 android relativelayout

因为我还在学习Android(而且看起来亚马逊说我要花2个月才拿到Hello,Android书)我仍然在做着简单的事情.使用ImageView点击RelativeLayout上的按钮,即可显示图标.创建它的代码如下:

private int mIconIdCounter = 1;
private ImageView addIcon(){
    ImageView item = new ImageView(this);
    item.setImageResource( R.drawable.tiles );
    item.setAdjustViewBounds(true);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
    if( mIconIdCounter != 1 ){
        params.addRule(RelativeLayout.RIGHT_OF, 1 );
    }
    item.setLayoutParams( params );
    item.setId( mIconIdCounter );
    ++m_IconIdCounter;
    return item;
}
Run Code Online (Sandbox Code Playgroud)

并且添加项目的代码是:

Button addButton = (Button)findViewById(R.id.add_new);
addButton.setOnClickListener( new OnClickListener(){
    @Override
    public void onClick(View view) {
        addContentView( addIcon(), new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
    }
});
Run Code Online (Sandbox Code Playgroud)

当我点击我的按钮时会发生什么,所有新创建的视图都放在另一个上面.我希望它们被放置在下一个元素的右侧.我在SO上快速搜索了与RelativeLayout相关的文章,并发现了一些相似的内容(这里,这里,这里,这里),但是这些内容解决了将内容引入RelativeView的问题,他们似乎没有解决定位问题.

我究竟做错了什么?

编辑:

我的主要xml看起来像:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:id="@+id/add_new"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add_new"
        android:layout_alignParentBottom="true" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

Kno*_*sos 8

看起来您可能正在将视图添加到布局xml的根而不是RelativeLayout.

你可以尝试:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout);
layout.addView(addIcon());
Run Code Online (Sandbox Code Playgroud)