【问题标题】:Dynamically adding content to RelativeLayout动态添加内容到RelativeLayout
【发布时间】:2015-03-09 03:08:33
【问题描述】:

由于我还只是在学习 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 ) );
    }
});

当我点击我的按钮时,所有新创建的视图都被放置在另一个之上。我希望它们被放置在下一个元素的右侧。我在 SO 上快速搜索了与 RelativeLayout 相关的文章,发现了一些类似的文章(herehereherehere),但是虽然这些解决了将内容放入 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>

【问题讨论】:

    标签: android android-relativelayout


    【解决方案1】:

    看起来您可能会将视图添加到布局 xml 的根目录而不是 RelativeLayout。

    你可以试试:

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

    【讨论】:

    • 所以如果我的主要 xml 只不过是一个 RelativeLayout 和一个 Button,我该如何访问它?就像(R.id.main)一样?我会更新我的问题给你看。
    • 你需要给你的 relativelayout 一个 ID 为 android:id="+@id/my_layout"。然后,您可以在代码中实例化您的布局。以便您可以向其添加视图。希望有帮助!
    【解决方案2】:

    您正在函数调用中创建新的相对布局。因此,每次创建新的相对布局时,它都会在单击按钮时添加到视图中。使用常见的相对布局。

    【讨论】:

    • 他每次都在创建新的布局参数,而不是新的布局。问题出在 addContentView 上。
    猜你喜欢
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多