addView () для inflateLayout - PullRequest
       15

addView () для inflateLayout

0 голосов
/ 03 марта 2012

Вот мой код:

        LinearLayout ll = (LinearLayout) View.inflate(TabAndPlay.this, R.layout.current_play, null);

        TextView tv = new TextView(TabAndPlay.this);
        tv.setText("hallo");
        tv.setBackgroundColor(Color.GRAY);
        ll.addView(tv);

current_play.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/aktuelle_spiele"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

R.id.llPlay (там 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:orientation="vertical" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip">

        <LinearLayout
            android:id="@+id/llPlay"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

        </LinearLayout>

    </ScrollView>

</LinearLayout>

Вот onOptionsItemSelected ()

        case R.id.current_play:
            LinearLayout mainLayout = (LinearLayout) findViewById(R.id.llPlay);
            mainLayout.removeAllViews();
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(R.layout.current_play, mainLayout, true); 
            return true;

Если я нажму на мой пункт меню, все мои текущие представления на R.id.llPlays будут удалены! Кнопка из current_play показывается. Но TextView из "Здесь мой код" не отображается .. Зачем? Где моя ошибка?

Ответы [ 2 ]

0 голосов
/ 03 марта 2012

Вы забыли параметры макета для этого текстового представления.

LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(wrap_content,wrap_content);

Затем при добавлении

ll.addView(tv);
0 голосов
/ 03 марта 2012

Ваш вопрос неоднозначен, поэтому я угадаю ответ:

В вашем onOptionsItemSelected() вы ищете LinearLayout с идентификатором R.id.llPlay и удаляете из него все дочерние представления с помощью removeAllViews(), а затем надуваете R.layout.current_play и настраиваете свой макет, чтобы получить LinearLayout (aktuelle_spiele) с Button, но также с TextView (для которого вы устанавливаете текст "Hallo"). Проблема в том, что когда вы раздуваете макет, вы надуваете только те представления, которые находятся на этом макете в данный момент. Если вы хотите, чтобы ваш макет также содержал TextView, который вы встроили в код, тогда у вас есть 2 варианта:

1 Добавьте TextView непосредственно в макет current_play.xml, а также добавьте к нему идентификатор, чтобы впоследствии вы могли извлечь этот TextViewfindViewById(R.id.the_text)) и установить текст «Hallo»:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/aktuelle_spiele"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    <TextView 
        android:id="@+id/the_text" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />    
</LinearLayout>

Изменить:

2 Затем динамически создавайте макеты там, где вы хотите, но сохраняйте ссылку на это раздутое представление. Итак, если вы создаете вид, подобный этому:

 LinearLayout ll = (LinearLayout) View.inflate(TabAndPlay.this, R.layout.current_play, null);
        TextView tv = new TextView(TabAndPlay.this);
        tv.setText("hallo");
        tv.setBackgroundColor(Color.GRAY);
        ll.addView(tv);

затем удерживайте ссылку на это завышенное представление ll и передайте ее в обратном вызове onOptionsItemSelected() в основной макет:

case R.id.current_play:
            LinearLayout mainLayout = (LinearLayout) findViewById(R.id.llPlay);
            mainLayout.removeAllViews();
            mainLayout.add(ll);
            return true;
...