Подтвердить что ты не робот

Значок в закладке не отображается

Я начинаю с 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>

4b9b3361

Ответ 1

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

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

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

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

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

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

Вот важная часть того, как настроить индикатор (this = текущая активность):

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

Это простой способ показать текст и значок в 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 и прекрасно работал.

Удачи:)

Ответ 3

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

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

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

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

Ответ 4

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

  • с помощью setIndicator ( "TAB" ) для установки только текста.
  • с помощью 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]));

    }