为什么在布局 xml 中将 RelativeLayout 的 "layout_width" 设置为固定值不起作用?

Why setting "layout_width" of RelativeLayout to a fixed value in layout xml not working?

我想将一个RelativeLayout的宽度和高度设置为一个固定值。我的 item_view.xml 看起来像这样;

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:orientation="vertical"
    android:background="#00ff00">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="abc"/>

</RelativeLayout>

这里是 activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

最后是 MainActivity.java;

中的 generateView 函数
private void generateItemView()
{
    LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = layoutInflater.inflate(R.layout.item_view, null);

    RelativeLayout containerView = findViewById(R.id.container);
    containerView.addView(itemView);
}

这是结果;

如您所见,这不是 100dpX100dp 大小。

另一方面,如果我以编程方式执行此操作,它会起作用。这是更新后的 generateView 函数;

private void generateItemView()
{
    LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = layoutInflater.inflate(R.layout.item_view, null);

    int sizeDp = 100;
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int sizePx = Math.round(sizeDp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(sizePx, sizePx);
    itemView.setLayoutParams(params);

    RelativeLayout containerView = findViewById(R.id.container);
    containerView.addView(itemView);
}

而且效果很好...

我的问题是,为什么我们不能在布局 xml 文件中使用 layout_width 和 layout_height 属性?

您可能需要在对 layoutinflator.inflate 的调用中设置父级:layoutinflator.inflate(R.layout.item_view, containerview, false);。您还需要重新安排代码,因此这是 运行 在您实例化 containerview 之后。

有关发生这种情况的原因的更详细答案,请查看

您的问题出在这一行:

View itemView = layoutInflater.inflate(R.layout.item_view, null);

当您将 null 作为父项传递时,任何 layout_ 属性都将被忽略。为了保留它们并使它们生效,您必须传递父级。

View itemView = layoutInflater.inflate(R.layout.item_view, containerView, false);

您的 IDE 应该 就此案例向您发出警告: