我已经阅读了可能所有的帖子和文档,但我仍然无法解决这个问题。
我想用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>
请帮忙。这会让我发疯的!
您忘记指定LayoutParameters
对于新添加的视图。
LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
TextView text=new TextView(this);
text.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text.setText("test");
layout.addView(text);
EDIT
The GridView
id 为@+id/gridview
定义的布局高度为fill_parent
,让您没有空间添加新视图。将其高度更改为wrap_content
可能会解决你的问题。
将我的评论添加到这篇文章中以帮助其他人轻松验证解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)