这个问题似乎已经被问了十几次了,但我一直无法从他们那里推断出解决方案。
我有一个名为 tile.xml
的布局,如下所示:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:text="May Fong Robinson"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:text="Beautiful star-shaped spillway, Kechut Reservoir, Jermuk, Armenia"
android:textAppearance="?android:attr/textAppearanceMedium" />
我需要添加一个名为 feed.xml
的 View ,我将其声明为 ScrollView
因为我想在其中包含多个对象,所以我可以垂直滚动它们。这是我的 feed.xml
文件:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:background="#F1F1F1"
android:layout_height="fill_parent" >
</ScrollView>
我想在更改 的文本时将我的“tile”从
动态。tile.xml
动态添加到我的“feed”feed.xml
View TextViews
我该怎么做?谢谢
新的 feed.xml
:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#F1F1F1" >
<LinearLayout
android:id="@+id/tiles"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
</ScrollView>
...和新的 tile.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:text="May Fong Robinson"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:text="Beautiful star-shaped spillway, Kechut Reservoir, Jermuk, Armenia"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
最佳答案
首先,在布局中添加 2 个 TextView。
然后,在您的代码中,您想要动态添加 TextView 的地方执行以下操作:
ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.tile, null);
scroll.addView(view);
要访问 TextView,您必须执行以下操作:
TextView textView1 = (TextView) view.findViewById(R.id.textView1);
textView1.setText("");
还要确保在 XML 文件中为您的 TextView 提供不同的 ID。目前他们都是textView1
关于android - 将布局动态添加到 ScrollView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11958430/