Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding content to RelativeLayout

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>
like image 433
wheaties Avatar asked Feb 25 '23 18:02

wheaties


1 Answers

It looks like you might be adding the view to the root of the layout xml instead of the RelativeLayout.

You could try:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout);
layout.addView(addIcon());
like image 150
Knossos Avatar answered Mar 08 '23 03:03

Knossos