Как использовать 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>
Пожалуйста помоги. Это сводит меня с ума!
Ответы
Ответ 1
Вы забыли указать 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);
ИЗМЕНИТЬ
GridView
с идентификатором @+id/gridview
определяется с высотой макета fill_parent
, оставляя вам свободное место для добавления нового представления. Изменение высоты до wrap_content
может решить вашу проблему.
Добавление комментария к этому сообщению, чтобы помочь другим легко проверить решение.
Ответ 2
У меня была такая же проблема, и я потратил несколько раз на то, чтобы найти причину.
Моя ошибка заключалась в том, что я добавлял CustomView, у которого match_parent был установлен как высота.
Я надеюсь сэкономить драгоценное время любому, кто сделал эту глупую досадную ошибку:)
TextView tv = new TextView(this);
lytMarks.addView(tv);
CustomView cv = new CustomView(this, someObject);
lytMarks.addView(cv); // <-- This one had height = match_parent!!
EditText et = new EditText(this);
lytMarks.addView(et);
Ответ 3
Ваше содержимое linearLayout находится над родительским представлением. поэтому вам нужно использовать ScrollView.
например:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/main1"
android:orientation="vertical">
<TextView
android:id="@+id/app_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/app_title"
android:textColor="#FFF"
android:textSize="25dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:text="@string/main_screen_counter_title"
android:textColor="#FFF"
android:textSize="15dp" />
<TextView
android:id="@+id/frontScreenCounter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/reading"
android:textColor="#FFF"
android:textSize="33dp" />
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:textColor="#888"
android:verticalSpacing="10dp" />
</LinearLayout>
</ScrollView>
Ответ 4
Я не помню, но, возможно, есть какой-либо метод "обновления" для повторной загрузки макета.
Попробуйте layout.invalidate();