2010-11-24 136 views
4

因为我还只是在学习Android(而且看起来亚马逊说它会在2个月之后才会出现Hello,Android的书),我仍然在做简单的事情。使用ImageView在RelativeLayout上点击一个按钮,我就没有问题了。创建它的代码如下:向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)); 
    } 
}); 

当我点击我的按钮会发生什么是所有新创建的视图被放置在彼此顶上。我希望将它们放在下一个元素的右侧。我在SO上搜索了与RelativeLayout有关的文章,并发现了一些类似的文章(here,here,herehere),但是当这些内容进入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> 

回答

8

看起来你可能会被添加视图布局XML,而不是RelativeLayout的根。

你可以尝试:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout); 
layout.addView(addIcon()); 
+0

因此,如果我的主要xml只不过是一个RelativeLayout和一个Button,它如何访问它?就像(R.id.main)?我会更新我的问题向你展示。 – wheaties 2010-11-24 19:07:50

+0

你需要给你的relativelayout一个ID为android:id =“+ @ id/my_layout”。 然后你可以在你的代码中实例化你的布局。以便您可以添加视图。 希望有帮助! – Knossos 2010-11-24 21:00:39

0

要创建函数调用内部新的相对布局。所以每次创建新的相对布局,并在单击按钮时添加到视图中。使用常见的相对布局。