我读过大概所有的文章和文档,但我仍然无法解决这个问题。addView不起作用
我想使用addView()方法添加视图到现有的(运行)布局,但由于某种原因,我不能。我知道这应该是简单而基本的,但我仍然无法做到。所以,请帮助我。
下面是一个代码:
LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
TextView text=new TextView(this);
text.setText("test");
layout.addView(text);
这是一个代码,结果是,我只显示其在XML文件中定义的视图。我没有添加这个新的观点。 当我调试时,我看到这个添加的视图作为父项的一个孩子,我已经添加它但它不显示。
这里的main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/main1" >
<TextView android:id="@+id/app_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="@string/app_title"
android:textSize="25dp"
android:gravity="center_horizontal"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/main_screen_counter_title"
android:textSize="15dp"
android:textColor="#FFF"
android:gravity="center_horizontal"/>
<TextView android:id="@+id/frontScreenCounter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="@string/reading"
android:textSize="33dp"
android:gravity="center_horizontal" />
<GridView android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:textColor="#888"
/>
</LinearLayout>
请帮助。这会让我疯狂!
您可以加入您要添加的'TextView'布局? – Luksprog 2012-07-09 15:35:49
Hey Luksprog,这是因为在LinearLayout属性中android:layout_height =“fill_parent”。我现在已经显示文字,但在屏幕的底部。如何把它放在顶部?你帮了我。间接,但仍然。 Tnx很多。 – Majstor 2012-07-09 15:45:43
如果你想把'TextView'放在某个位置,你应该使用'addView'方法的另一种方法,它接受一个int,放置新View的位置,像这样:addView(text, 0);' – Luksprog 2012-07-09 15:49:03