addView не работает
Я прочитал, вероятно, все сообщения и документацию, но я все еще не могу решить эту проблему.
Я хочу использовать метод addView () для добавления представления в существующий (работающий) макет, но по какой-то причине я не могу. Я знаю, что это должно быть легко и просто, но все же я не могу этого сделать. Так что, пожалуйста, помогите мне.
вот код:
LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
        TextView text=new TextView(this);
        text.setText("test");
        layout.addView(text);
это код, и в результате я отобразил только представления, определенные в xml-файле. У меня нет этого нового взгляда. добавлен. Когда я отлаживаю, я вижу это добавленное представление как дочернее родительское, к которому я его добавил, Но оно не отображается.
здесь главный.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>
пожалуйста, помогите. Это сведет меня с ума!
4 ответов
вы забыли указать 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 может решить вашу проблему.
добавление моего комментария к этому сообщению, чтобы помочь другим легко проверить решение.
У меня была та же проблема, и я потратил несколько времени на поиск причины.
моя вина, что я был добавив пользовательские, которые присваиваем набор высоты.
Я надеюсь, чтобы сэкономить драгоценное время всем, кто сделал эту глупую досадную ошибку :)
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);
содержимое 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>
Я не могу вспомнить, но, возможно, есть какой-либо метод "обновления" для загрузки макета.
попробовать макет.признать недействительными();