以编程方式在 Relativelayout 中设置边距

setMargrin in Relativelayout Programmatically

我想通过单击按钮将带有边距的文本视图添加到 Relativelayout 中,但是每当我将 setMargins 添加到 LayoutParams 时,它会使 TextView 消失。这是我的代码

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/test11">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/test"
        android:onClick="onClick"
        android:text="asdf"/>
</RelativeLayout>

这是我的代码:

    public class tet extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
    }

    public void onClick(View v){
        TextView textView = new TextView(this);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        layoutParams.setMargins(30, 30, 30, 30);

        textView.setText("asdf");
        textView.setLayoutParams(layoutParams);
        ((RelativeLayout)findViewById(R.id.test11)).addView(textView);
    }
}

我 99% 确定您的 TextView 在 Button 后面。有几个问题:

layoutParams.setMargins(30, 30, 30, 30);

这设置了以像素为单位的边距!如果您在 xml 布局中设置边距,它们通常设置为 dp(您可以在那里选择单位)。如果你想在你的代码中使用 dp,你必须转换 px => dp(here 你可以找到一个例子)。

其次:您使用的是RelativeLayout,因此所有Views在您的布局中都是相对排列的。您没有向 TextView 提供任何信息,因此它将被放置在其父级的 left/top 处(因此在您的 Button 后面)。

尝试将 RelativeLayout 换成 LinearLayout 或提供额外的排列信息。

对于未来:Android SDK 提供的 Hierarchyviewer 可以轻松解决此类问题 ("my view is missing")。