因为我仍然只是在学习 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;
}
添加项目的代码是:
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 ) );
}
});
当我点击我的按钮时,所有新创建的 View 都被放置在彼此之上。我希望将它们放置在下一个元素的右侧。我在 SO 上快速搜索了与 RelativeLayout 相关的文章,发现了一些类似的文章( here 、 here 、 here 和 here ),但是虽然这些解决了将内容放入 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>
最佳答案
看起来您可能会将 View 添加到布局 xml 而不是 RelativeLayout 的根。
你可以试试:
RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout);
layout.addView(addIcon());
关于android - 动态添加内容到 RelativeLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269660/