Android: 在嵌套布局中动态添加视图

5
我有一个结构如下的abc.xml文件。
<ScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 <RelativeView
   android:layout_width="match_parent"
   android:layout_height="wrap_content">
  <LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
  </LinearLayout>
 </RelativeLayout>
</ScrollView>

我想在线性布局中动态添加文本视图。以下是我的代码。我没有收到任何错误,但我没有得到期望的结果。

LayoutInflater Inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = Inflater.inflate(R.layout.abc, null);

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);

        TextView Tag = new TextView(getActivity());
        Tag.setText("textString");
        Tag.setBackgroundResource(R.color.bg_color);
        Tag.setTextAppearance(getActivity(), R.style.SmallFont);
        layout.addView(Tag);

为什么你在使用RelativeLayout? - Hardik Joshi
我在相对布局中还有其他视图,例如文本视图和按钮视图。 - Shah
3个回答

6
你的XML应该是:

<ScrollView
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 <LinearLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical">
  <LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
  </LinearLayout>
 </LinearLayout>
</ScrollView>

添加文本视图的Java代码如下:

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
TextView Tag = new TextView(getActivity());
tag.setLayoutParams(params);
Tag.setText("textString");
Tag.setBackgroundResource(R.color.bg_color);
Tag.setTextAppearance(getActivity(), R.style.SmallFont);
layout.addView(Tag);

0

你必须给予,

android:layout_orientation="either horizontal or vertical"

到id为linear的线性布局。


0

我不知道你是否已经找到了答案,但我刚刚遇到了这个问题,并找到了一种方法。 我认为你需要按照以下方式调整一个位的布局:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <LinearLayout
                android:id="@+id/linear"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >
            </LinearLayout>
        </LinearLayout>

    </RelativeView>

</ScrollView>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接