5

我希望能够在代码中向已经存在的 xml 布局添加视图:

        LinearLayout ll = (LinearLayout) findViewById(R.layout.common_list);

        TextView tv = new TextView(this);
        tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        tv.setText("sample text");
        ll.addView(tv);

        setContentView(ll); 

在代码中创建一个新的 LinearLayout 时它可以工作,但是当使用上面代码中的 Resource 时它不会。

common_list.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Quick List"/>

</LinearLayout>
4

1 回答 1

7

尝试使用 LayoutInflater

LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.common_list)
TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setText("sample text");
ll.addView(tv);

setContentView(ll);

如果这不起作用,请从 Logcat 添加错误。

此外,您应该在 common_list.xml 中的 LinearLayout 中将属性从 android:layout_width="fill_parent" 更改为 android:layout_width="wrap_content" 并对 common_list.xml 中的 TextView 执行相同的操作

为什么?因为您的布局是横向的,它会填满整个屏幕空间。您的 TextEdit 填充的空间与您的布局一样多(因此在这种情况下,它是整个屏幕空间)。现在,当您添加另一个 TextView 时,它正在正确添加 - 在您的第一个 TextEdit 的右侧,所以它就像在屏幕外。要准确了解会发生什么:

-----------------
||-------------||---------------
||| TextViev1 ||||addedTextView|
||-------------||---------------
||             ||
||             ||
||             ||
||             ||
||             ||
||LinearLayout ||
||-------------||
|    screen     |
----------------

我也多次遇到这个问题。通常,如果您将 View 添加到布局并且您没有看到它(并且您没有收到错误),问题出在宽度/高度或位置(例如,当您使用 RelativeLayout 时)。

于 2011-09-01T11:52:49.133 回答