2012-05-24 3 views
17

Я начинаю с Android и когда пытаюсь сделать TabHost со значком и текстом. Только текст виден, если я оставил текст в пустом состоянии, можно увидеть значок. Я хочу видеть как на экране.Значок в закладке не отображается

Может ли кто-нибудь дать мне совет?

public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 

Usuario usu = new Usuario(); 
usu.nombre = "fsdf"; 
lista.add(usu); 

adaptador = new AdaptadorCelda(this,lista); 
ListView lstView = (ListView)findViewById(R.id.lista); 
lstView.setAdapter(adaptador); 

Button btn = (Button)findViewById(R.id.btnSalva); 

btn.setOnClickListener(onSave); 



Resources res = getResources(); 

TabHost tabs=(TabHost)findViewById(R.id.tabhost); 
tabs.setup(); 

TabHost.TabSpec spec=tabs.newTabSpec("mitab1"); 
spec.setContent(R.id.tab1); 
spec.setIndicator("",res.getDrawable(android.R.drawable.ic_menu_rotate)); 


tabs.addTab(spec); 

spec=tabs.newTabSpec("mitab2"); 
spec.setContent(R.id.tab2); 
spec.setIndicator("ddd", 
     res.getDrawable(android.R.drawable.presence_invisible)); 
tabs.addTab(spec); 

tabs.setCurrentTab(0); 

spec.setIndicator("",res.getDrawable(android.R.drawable.ic_menu_rotate)) In this case icon appears. 

spec.setIndicator("ddd", 
     res.getDrawable(android.R.drawable.presence_invisible)); 

и вот main.xml

<TabHost xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/tabhost" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<LinearLayout 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<TabWidget 
    android:id="@android:id/tabs" 
    android:layout_width="match_parent" 

    android:layout_height="wrap_content" /> 

<FrameLayout 
    android:id="@android:id/tabcontent" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/tab1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" > 
     <TextView 
      android:id="@+id/lblNombre" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_marginTop="17dp" 
      android:text="Nombre" 
      android:textAppearance="?android:attr/textAppearanceLarge" /> 

     <EditText 
      android:id="@+id/txtNombre" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignTop="@+id/lblNombre" 
      android:layout_marginLeft="35dp" 
      android:layout_toRightOf="@+id/lblNombre" 
      android:ems="10" > 

      <requestFocus /> 
     </EditText> 

     <EditText 
      android:id="@+id/txtApellido" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignLeft="@+id/txtNombre" 
      android:layout_below="@+id/txtNombre" 
      android:ems="10" /> 

     <TextView 
      android:id="@+id/lblApellido" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignBottom="@+id/txtApellido" 
      android:layout_alignParentLeft="true" 
      android:text="Apellidos" 
      android:textAppearance="?android:attr/textAppearanceLarge" /> 

     <RadioGroup 
      android:id="@+id/tipos" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/txtApellido" 
      android:layout_marginTop="35dp" 
      android:layout_toLeftOf="@+id/txtApellido" > 

      <RadioButton 
       android:id="@+id/rdbAlta" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="alta" /> 

      <RadioButton 
       android:id="@+id/rdbBaja" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="baja" /> 

      <RadioButton 
       android:id="@+id/rdbTramite" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="tramite" /> 
     </RadioGroup> 

     <Button 
      android:id="@+id/btnSalva" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignLeft="@+id/txtApellido" 
      android:layout_alignTop="@+id/tipos" 
      android:layout_marginLeft="58dp" 
      android:layout_marginTop="30dp" 
      android:text="Button" /> 

     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true" 
      android:layout_below="@+id/txtApellido" 
      android:src="@drawable/ic_menu_chart" /> 

    </RelativeLayout> 

    <LinearLayout 
     android:id="@+id/tab2" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" > 

     <ListView 
      android:id="@+id/lista" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_below="@+id/tipos" 
      android:layout_marginTop="24dp" > 
     </ListView> 
    </LinearLayout> 
</FrameLayout> 

+2

Покажите нам, что вы делаете –

+0

пожалуйста, дайте использовать больше информации .. –

+0

извини ребята, я немного новичка. – theholy

ответ

52

Проверили Вы Ваше приложение на устройстве под управлением Ice Cream Sandwich? Недавно я заметил, что по умолчанию TabHost ведет себя по-разному в зависимости от целевого устройства и версии платформы Android.

Запуск приложение, которое обеспечивает иконку и текст setIndicator (как в источнике от вопроса), имел следующий результат теста:

  • телефон с Android 2.1: как значок и текст, где показано (Надпись под иконкой, как ожидалось)
  • Телефон с 4.0.3: Значки не показывались, и был только текст.
  • Планшет работает под управлением ICS: вкладки, где показаны с иконкой и текстом

Как выяснился, тоже, заменив этикетку с пустой строкой в иконках появились на телефоне - но тогда пользователь будет нужно угадать значение значков. Кроме того: при запуске этой версии приложения на телефоне pre ICS: вкладки сохраняют свой размер и оставляют пустую область под изображением.

Чтобы изменить это устройство, приводимое решение о том, сколько места язычки должны получить, я нашел решение в этом tutorial on how to customize tabs:

Прежде всего, необходимо предоставить вашему собственный индикатор Язычок макет ("макет/tab_indicator.xml "в учебнике), включая ImageView и TextView. Затем вы говорите TabSpec, чтобы использовать это через setIndicator. И voilà: вы получаете значок и ярлык на телефоне с помощью ICS.

Вот важная часть о том, как установить индикатор (это = текущую деятельность):

TabHost.TabSpec spec = this.getTabHost().newTabSpec(tag); 

View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false); 
((TextView) tabIndicator.findViewById(R.id.title)).setText(label); 
((ImageView) tabIndicator.findViewById(R.id.icon)).setImageResource(drawableResourceId); 

spec.setIndicator(tabIndicator); 

Если вам нравится один и тот же внешний вид вкладок на старых и новых телефонах имеет дополнительный вид здесь : http://jgilfelt.github.com/android-actionbarstylegenerator/. Эта страница генерирует изображения и стили для настройки панели действий, включая вкладки, и помогла мне разобраться, как нужно определять фоновые изображения с 9 патчами.

+2

Блестящий, вы должны сделать учебники. Реальный легко читать и понимать. –

+0

Также я использую более современные фрагменты. Любая идея о том, как реализовать это в фрагментах вместо старой TabActivity? –

+2

Этот подход также отображает «тонкую линию» под изображением/текстом при выборе вкладки. –

2

Я стараюсь следующий способ сделать это, и это работает прекрасно:

  1. с помощью setIndicator («TAB»), чтобы установить только текст.
  2. с помощью setBackgroundDrawable (-) для установки значка.

Пример кода:

final TabHost    tabHost = (TabHost)findViewById(android.R.id.tabhost); 
    final Resources    res = getResources(); 
    int i; 

    tabHost.setup(); //Call setup() before adding tabs if loading TabHost using findViewById(). 

    TabHost.TabSpec ts = tabHost.newTabSpec("trackinfo"); 
    //ts.setIndicator("", res.getDrawable(R.drawable.icon_trackinfo)); 
    ts.setIndicator("Track Information"); 
    ts.setContent(R.id.tabTrackInfo); 
    tabHost.addTab(ts); 

    TabHost.TabSpec ts2 = tabHost.newTabSpec("collection"); 
    //ts2.setIndicator("", res.getDrawable(R.drawable.icon_collection_gray)); 
    ts2.setIndicator("My Collection"); 
    ts2.setContent(R.id.tabMyCollecton); 
    tabHost.addTab(ts2); 

    tabHost.setOnTabChangedListener(new OnTabChangeListener(){ 
     @Override 
     public void onTabChanged(String tabId) 
     { 
      if("trackinfo".equals(tabId)) { 
       // 
       TabWidget tw = (TabWidget)tabHost.findViewById(android.R.id.tabs); 
       View tabView = tw.getChildTabViewAt(0); 
       TextView tv = (TextView)tabView.findViewById(android.R.id.title); 
       tv.setTextColor(TabColor[0]); 
       tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_selected)); 

       tabView = tw.getChildTabViewAt(1); 
       tv = (TextView)tabView.findViewById(android.R.id.title); 
       tv.setTextColor(TabColor[1]); 

       tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_gray)); 
      } 
      if("collection".equals(tabId)) { 
       // 
       TabWidget tw = (TabWidget)tabHost.findViewById(android.R.id.tabs); 
       View tabView = tw.getChildTabViewAt(0); 
       TextView tv = (TextView)tabView.findViewById(android.R.id.title); 
       tv.setTextColor(TabColor[1]); 
       tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_gray)); 

       tabView = tw.getChildTabViewAt(1); 
       tv = (TextView)tabView.findViewById(android.R.id.title); 
       tv.setTextColor(TabColor[0]); 
       tabView.setBackgroundDrawable(res.getDrawable(R.drawable.icon_selected)); 

     } 
     }}); // END OF tabHost.setOnTabChangedListener 

    // After Tabs being added 
    // change font settings 
    TabWidget tw = (TabWidget)tabHost.findViewById(android.R.id.tabs); 
    for(i=0;i<2;i++) 
    { 
     View tabView = tw.getChildTabViewAt(i); 
     TextView tv = (TextView)tabView.findViewById(android.R.id.title); 
     tv.setHeight(25); 
     tv.setTextColor(TabColor[i]); 
     tv.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC); 
     tv.setTextSize(20);  
     tabView.setBackgroundDrawable(res.getDrawable(TabIcon[i])); 

    } 
6

Существует еще одно очень простое решение для этого.

Кажется, что проблема заключается в новой теме Голо и TabWidget. Так что вы должны сделать, это определить Хола тему в папке values-v11, но со старым TabWidget стиля, как это:

<style name="MyAppTheme" parent="@android:style/Theme.Holo.NoActionBar"> 
    <item name="android:tabWidgetStyle">@android:style/Widget.TabWidget</item> 
</style> 

Это работает для меня, надеюсь, что это поможет кому-то.

+0

Вам также нужно добавить эту строку в ** values-v14 ** и папку с верхней версией. – biswajitGhosh

7

Это простой способ показать текст и значок в ICS. После того, как настроить на Tabhost, я называю следующие методы:

setTabIcon(mTabHost, 0, R.drawable.ic_tab1); //for Tab 1 
setTabIcon(mTabHost, 1, R.drawable.ic_tab2); //for Tab 2 

public void setTabIcon(TabHost tabHost, int tabIndex, int iconResource) { 
    ImageView tabImageView = (ImageView) tabHost.getTabWidget().getChildTabViewAt(tabIndex).findViewById(android.R.id.icon); 
    tabImageView.setVisibility(View.VISIBLE); 
    tabImageView.setImageResource(iconResource); 
} 

Если вы хотите более продвинутое решение, необходимо создать макет как @sunadorer рекомендуют. Моя рекомендация состоит в том, что вы можете создать свой макет, используя макет темы голограммы, ищите файл на своем sdk_dir/platform/android-14/data/res/layout/tab_indicator_holo.xml.

Мой передовое решение является следующим, вам нужно создать макет, как это:

tab_indicator.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_height="wrap_content" 
       android:orientation="vertical" 
       android:paddingTop="5dp" 
       android:paddingBottom="5dp" 
       style="@android:style/Widget.Holo.Tab"> 

    <ImageView 
     android:id="@android:id/icon" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:visibility="visible" /> 

    <TextView 
     android:id="@android:id/title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     style="@android:style/Widget.Holo.ActionBar.TabText" /> 

</LinearLayout> 

В вашей деятельности или фрагмента, создать следующую функцию:

public View createTabIndicator(LayoutInflater inflater, TabHost tabHost, int textResource, int iconResource) { 
    View tabIndicator = inflater.inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false); 
    ((TextView) tabIndicator.findViewById(android.R.id.title)).setText(textResource); 
    ((ImageView) tabIndicator.findViewById(android.R.id.icon)).setImageResource(iconResource); 
    return tabIndicator; 
} 

И, наконец, при создании своей вкладки в своей деятельности или фрагменте используйте следующий код:

mTabHost.addTab(
    mTabHost.newTabSpec("tab1") 
    .setIndicator(createTabIndicator(inflater, mTabHost, R.string.tab1, R.drawable.ic_tab1)) 
    .setContent(R.id.tab1) 
); 

Я протестировал это решение в ICS и отлично работает.

Удача :)

+1

i m ошибка в этой строке NPE: ImageView tabImageView = (ImageView) tabHost.getTabWidget(). GetChildTabViewAt (tabIndex) .findViewById (android.R.id.icon); – user3233280

Смежные вопросы