Android中未动态加载边框XML

Android中未动态加载边框XML,android,css,xml,android-layout,Android,Css,Xml,Android Layout,我正在尝试设置动态生成的RelativeLayout边框。出于某种原因,当我在活动XML中手动添加它时,它工作得非常好,但当我尝试动态添加它时,它不会显示出来 border.xml位于drawables文件夹中 <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item>

我正在尝试设置动态生成的RelativeLayout边框。出于某种原因,当我在活动XML中手动添加它时,它工作得非常好,但当我尝试动态添加它时,它不会显示出来

border.xml位于drawables文件夹中

<?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>

我非常感谢你的帮助!我已尝试将文本视图加载到LinearLayout,效果很好。但是RelativeLayout不显示边框(不过它确实加载了!)

你只需要一点修护

在代码中,将
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
,它将具有与其父对象相同的高度。您可以根据需要使用这些值来调整您的案例。不要忘记
重力
参数,您也可以动态配置

那么,为什么不在XML中定义边界?为什么不直接在RelativeLayout上设置边界?因为我实际上不知道动态加载它们时会有多少边界。第二个问题呢?你试过了吗?我不知道怎么做,我想我需要单独定义drawable,然后用它作为背景。我希望RelativeLayout只有一个底部黑色边框。
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);
}
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);