代码之家  ›  专栏  ›  技术社区  ›  wheaties

动态向RelativeLayout添加内容

  •  4
  • wheaties  · 技术社区  · 15 年前

    因为我还在学习安卓(似乎亚马逊说要等两个月才能收到安卓的问候书),所以我仍然在做一些简单的事情。我可以通过单击相对布局上的按钮来显示图标,使用 ImageView . 创建它的代码如下:

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

    添加项目的代码是:

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

    当我单击我的按钮时,会发生的事情是所有新创建的视图都被放置在另一个视图之上。我想把它们放在下一个元素的右边。我快速搜索了一下有关相对布局的文章,发现了一些相似的( here , here , here here )但是,尽管这些解决了将内容放入相对视图的问题,但它们似乎并没有解决定位方面的问题。

    我做错什么了?

    编辑:

    我的主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>
    
    2 回复  |  直到 11 年前
        1
  •  8
  •   Knossos    15 年前

    看起来您可能正在将视图添加到布局XML的根目录,而不是相对布局。

    你可以试试:

    RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout);
    layout.addView(addIcon());
    
        2
  •  0
  •   David    15 年前

    您正在函数调用内创建新的相对布局。所以每次创建新的相对布局,并在单击按钮时将其添加到视图中。使用公共相对布局。