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

标签 android dynamic view android-linearlayout

我有一个具有以下结构的 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>

我想将 TextView 动态添加到线性布局。下面是我的代码。我没有收到任何错误,但没有得到想要的结果。

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);

最佳答案

你的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>

添加 TextView 的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);

关于Android:在嵌套布局中动态添加 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656208/

相关文章:

c# - Dapper - 如何使用动态对象

sql - 可以嵌套数据库 View 吗?

java - 如何在 Android 中访问 View 的小部件?

android - 使用 --prod 和 --release 构建 Ionic 3 Angular 4 应用程序时出现空白屏幕

android - 使 recyclerView 项目适合屏幕

java - 您如何使用 Data Snapshot 跨多个子节点检索数据?

android - 具有旋转、放大、缩小和在 android 中触摸移动的自定义 textview?

c - 为什么 C 不是动态语言?

variables - Golang 动态变量引用

ios - 如何创建一个无需应用商店更新即可远程更新的 View