Почему рисуемый элемент внутри вкладки не будет виден?

У меня есть собственный TabHost, который добавляет такие вкладки

private void setTab(View view, String tag, Intent intent)
{
  View tabView = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
  TextView tv = (TextView) view.findViewById(R.id.tabsText);
  tv.setText(tag);
  TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabView)
                     .setContent(intent);
  mTabHost.addTab(setContent);
}

где mTabHost — хост вкладки, а tabs_bg.xml просто имеет текстовое представление в линейном макете. (Мой основной макет такой же, как Пример макета вкладки; я просто пытаюсь использовать небольшие текстовые вкладки.) Моя информационная вкладка вызывается следующим образом:

intent = new Intent().setClass(this, AboutScreen.class);
setTab(new TextView(this), "about", intent);

AboutScreen расширяет Activity, и все, что он делает, это устанавливает ContentView для этого

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent" android:layout_height="wrap_content">    
    <TextView android:id="@+id/AboutUsTitle" 
      android:textColor="#ffffffff" android:text="@string/about_title"
      android:layout_height="wrap_content" android:layout_width="fill_parent"
      android:layout_gravity="center" android:gravity="center"
      android:background="@drawable/about_title"/>
  </LinearLayout>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:padding="15dip">
    <TextView android:id="@+id/AboutContents" 
      android:text="@string/about_contents" android:layout_height="wrap_content"
      android:layout_width="wrap_content"/>
  </LinearLayout>
</LinearLayout>

где @drawable/about_title это:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient
    android:startColor="#ffffffff"
    android:endColor="#ff333333"
    android:angle="90"/>
</shape>

Этот рисунок не отображается внутри FrameLayout. Все остальное отображается корректно. Любые идеи, что я делаю неправильно?


EDIT: если я установлю это программно

TextView tvAboutUsTitle = (TextView) findViewById(R.id.AboutUsTitle);
tvAboutUsTitle.setBackgroundResource(R.drawable.about_title);

он появляется. Почему это отличается от установки в xml?


person Ben Williams    schedule 20.04.2011    source источник
comment
Одна вещь, которую я вижу, отличается от имени вашего рисунка - «about_title» против «градиента». Являются ли они одинаковыми?   -  person f20k    schedule 02.05.2011
comment
Ой! Да, это моя вина, что я копирую вещи в новые файлы во время тестирования, если использование ссылок @color имеет значение. Я отредактирую оригинал, чтобы исправить это.   -  person Ben Williams    schedule 03.05.2011


Ответы (3)


я нигде не вижу, чтобы вы использовали телевизор (TextView), если только он не отсутствует в этом фрагменте кода?

Вот пример того, как я настраиваю 3 вкладки в действии, которое может вам помочь.

EDIT: я забыл упомянуть. В этом коде мне также нужно то, что, я думаю, вы хотите, настраиваемая вкладка из одной строки.

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this.getApplicationContext();

    application = ((rbApplication)getApplicationContext());

    setContentView(R.layout.channellist);    

    new DownloadTask().execute();

    setupTabs();


}

    public void setupTabs() {
        TabHost tabHost = getTabHost();  // The activity TabHost    
        tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
        TabHost.TabSpec spec;  // Reusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab

        // Initialize a TabSpec for each tab and add it to the TabHost
        intent = new Intent().setClass(application, ChannelListSubscribed.class);
        spec = tabHost.newTabSpec("subscribed");
        View customTabView1 = createTabView(application, "Subscribed");
        spec.setIndicator(customTabView1);
        spec.setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(application, ChannelListNonSubscribed.class);
        spec = tabHost.newTabSpec("nonsubscribed");
        View customTabView2 = createTabView(application, "Find More");
        spec.setIndicator(customTabView2);
        spec.setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(application,ChannelListFeatured.class);
        spec = tabHost.newTabSpec("featured");
        View customTabView3 = createTabView(application, "Featured");
        spec.setIndicator(customTabView3);
        spec.setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTab(0);
    }

    private static View createTabView(final Context context, final String tabLabel) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item, null);
        TextView tv = (TextView) view.findViewById(R.id.tab_label);

        tv.setText(tabLabel);
        return view;
    }

tab_item.xml

    <?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="fill_parent" 
    android:padding="10dip" 
    android:gravity="center" 
    android:orientation="vertical"
    android:background="@drawable/tab_bg_selector"> 
    <TextView
        android:id="@+id/tab_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp" 
        android:textColor="@drawable/tab_text_selector"/>
</LinearLayout>
person wired00    schedule 20.04.2011
comment
Я делаю tv.setText(tag); сразу после просмотра текста. Мой tabs_bg.xml выглядит так же, как ваш tab_item.xml (мой @+id/tabsText — это ваш @+id/tab_label.) Если я вызову AboutScreen в качестве основного действия вместо макета вкладки, градиент появится. Если я вызову его внутри макета вкладки, это не так. - person Ben Williams; 21.04.2011

У меня были проблемы, когда представление не отображалось достаточно большим из-за того, что его размер, по-видимому, определялся до того, как стало известно его содержимое, даже если все это хранится в xml (со ссылками на строки)

Вы пытались установить layout_height и width в числовые значения (или даже «заполнить родителя», чтобы увидеть, так ли это?

Кроме того, я бы упростил макет, чтобы удалить вложенные LinearLayouts? поскольку они кажутся ненужными из-за того, что каждый содержит только один TextView

person FrinkTheBrave    schedule 01.05.2011
comment
Я попытался изменить layout_height/widths на числовые значения, как dp, так и px, но это не имеет значения - они отображаются, если вы смотрите на активность напрямую, но не когда она загружается на вкладку, если вы специально не установили ее программно . Также не имеет значения, делаю ли я это с посторонними LinearLayouts или без них (они есть только потому, что все мои действия используют один и тот же базовый макет, а другие экраны содержат больше, чем просто одно текстовое представление, поэтому их использование здесь имеет смысл. ) - person Ben Williams; 02.05.2011

Так как мы все равно сейчас не используем представление вкладок, я собираюсь закрыть это, так как это

TextView tvAboutUsTitle = (TextView) findViewById(R.id.AboutUsTitle);
tvAboutUsTitle.setBackgroundResource(R.drawable.about_title);

исправила проблему, которая у меня была в любом случае, даже если я действительно не знаю, почему.

person Ben Williams    schedule 12.05.2011