Dynamically adding content to RelativeLayout

倾然丶 夕夏残阳落幕 提交于 2019-11-30 15:51:39

问题


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>

回答1:


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



回答2:


you are creating new relative layout inside function call. So every time new relative layout created and it added in the view when click button . Use common relative layout.



来源:https://stackoverflow.com/questions/4269660/dynamically-adding-content-to-relativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!