边界XML未在Android中动态加载

时间:2014-09-16 00:23:54

标签: android css xml android-layout

我正在尝试设置动态生成的RelativeLayout边框。出于某种原因,当我在活动XML中手动完成它时,它可以很好地工作,但是当我尝试动态添加它时,它并没有显示出来。

位于drawables文件夹中的

border.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#000" />
        </shape>
    </item>
    <item android:bottom="1dp">
        <shape android:shape="rectangle">
            <solid android:color="#fff" />
        </shape>
    </item>
</layer-list>

活动XML文件

<RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="5px"
            android:paddingTop="5px"
            android:background="@drawable/border">

直接添加代码并将其附加到现有LinearLayout的代码

public void load(){

LinearLayout UsersContainer = (LinearLayout) findViewById(R.id.usersContainer);
RelativeLayout UserContainer = new RelativeLayout(this);
UserContainer.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
UserContainer.setPadding(0,5,5,0);
UserContainer.setBackgroundResource(R.drawable.border);
UsersContainer.addView(UserContainer);
}

我真的很感谢你的帮助!我已经尝试将TextView加载到LinearLayout,它工作正常。然而,RelativeLayout不显示边框(它确实加载!)。

1 个答案:

答案 0 :(得分:1)

你只需要一点修理。

在您的代码中,将load()方法更改为:

LinearLayout usersLinear = (LinearLayout) findViewById(R.id.usersContainer);
RelativeLayout userRelative = new RelativeLayout(this);
//you were setting your height value as RelativeLayout.LayoutParams.WRAP_CONTENT, I changed it //to RelativeLayout.LayoutParams.MATCH_PARENT
userRelative.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
//apply padding
userRelative.setPadding(0,5,5,0);
userRelative.setBackgroundResource(R.drawable.border);
usersLinear.addView(userRelative);

因此,您的代码正常运行,但您没有为动态生成的RelativeLayout应用正确的高度值,并且未在布局上显示,因为它是空的(其中没有子视图)。使用MATCH_PARENT时,它将与其父级具有相同的高度。您可以根据需要使用这些值进行调整以适应您的情况。并且不要忘记您也可以动态配置的Gravity参数。