4

Since I'm still just learning Android (and it appears Amazon says it'll be 2 months till I get the Hello, Android book) I'm still playing around with doing simple things. I have no problem getting an icon to display with the click of a button on my RelativeLayout using ImageView. The code for creating it is as follows:

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;
}

and the code to add the item is:

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 ) );
    }
});

When I click my button what happens is all the newly created views are placed atop one another. I'd like them to be placed to the right of the next element. I did a quick search on SO for articles relating to RelativeLayout and found some that were similar (here, here, here, and here) but while these addressed getting the content into the RelativeView they didn't seem to address the positioning aspect.

What am I doing wrong?

EDIT:

My main xml looks like:

<?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>
4

2 回答 2

8

看起来您可能会将视图添加到布局 xml 的根目录而不是 RelativeLayout。

你可以试试:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout);
layout.addView(addIcon());
于 2010-11-24T17:41:01.963 回答
0

您正在函数调用中创建新的相对布局。因此,每次创建新的相对布局时,它都会在单击按钮时添加到视图中。使用常见的相对布局。

于 2010-11-24T17:42:08.893 回答