Несколько дней пытался разгадать эту загадку (как сделать табы внизу экрана). Пробовал различные варианты. И, наконец, озарение!
Предыстория.
Хотелось сделать универсальный вариант, без использования deprecated методов и классов.
К тому же на каждый таб предполагалась обработка в отдельных классах. А использование Intent для загрузки классов требует setup'а с LocalActivityManager, который уже устарел.
Основной класс унаследован от FragmentActivity, который не в android.app, а в android.support.v4.app
FragmentTabHost mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
А табы представляют собой кнопки с картинкой и текстом (наподобие того, как выглядят табы в iPhone - iPhone likes tabs)
mTabHost.addTab(setupTab("Тест", R.drawable.test_tab),
TestFragment.class, null);
private TabSpec setupTab(final String tag, final int imageRes) {
return mTabHost.newTabSpec(tag).setIndicator(
createTabView(mTabHost.getContext(), tag, imageRes));
}
private View createTabView(final Context context, final String text,
final int imageRes) {
View view = LayoutInflater.from(context).inflate(
R.layout.tab_host_layout, null);
((TextView) view.findViewById(R.id.title)).setText(text);
((ImageView) view.findViewById(R.id.icon)).setImageResource(imageRes);
return view;
}
класс TestFragment унаследован от android.support.v4.app.Fragment
xml-файлы выглядят следующим образом:
основной:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="64dp" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
tab_host_layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:layout_weight="1"
android:background="@drawable/back_selector"
android:orientation="vertical" >
<ImageView
android:id="@+id/icon"
android:cropToPadding="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/title"
android:scaleType="center" />
<TextView
android:id="@+id/title"
android:textSize="12sp"
android:textColor="@drawable/text_colors_selector"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Основное извращение заключалось в том, что TabHost во всех примерах фигурирует как родительский тег по отношению ко всем остальным, а перенос TabWidget'а относительно FrameLayout'а давал нужный результат. С FragmentTabHost'ом пришлось поступить иначе и избавиться от TabWidget'a в итоге.
Предыстория.
Хотелось сделать универсальный вариант, без использования deprecated методов и классов.
К тому же на каждый таб предполагалась обработка в отдельных классах. А использование Intent для загрузки классов требует setup'а с LocalActivityManager, который уже устарел.
Основной класс унаследован от FragmentActivity, который не в android.app, а в android.support.v4.app
FragmentTabHost mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
А табы представляют собой кнопки с картинкой и текстом (наподобие того, как выглядят табы в iPhone - iPhone likes tabs)
mTabHost.addTab(setupTab("Тест", R.drawable.test_tab),
TestFragment.class, null);
private TabSpec setupTab(final String tag, final int imageRes) {
return mTabHost.newTabSpec(tag).setIndicator(
createTabView(mTabHost.getContext(), tag, imageRes));
}
private View createTabView(final Context context, final String text,
final int imageRes) {
View view = LayoutInflater.from(context).inflate(
R.layout.tab_host_layout, null);
((TextView) view.findViewById(R.id.title)).setText(text);
((ImageView) view.findViewById(R.id.icon)).setImageResource(imageRes);
return view;
}
класс TestFragment унаследован от android.support.v4.app.Fragment
xml-файлы выглядят следующим образом:
основной:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="64dp" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
tab_host_layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:layout_weight="1"
android:background="@drawable/back_selector"
android:orientation="vertical" >
<ImageView
android:id="@+id/icon"
android:cropToPadding="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/title"
android:scaleType="center" />
<TextView
android:id="@+id/title"
android:textSize="12sp"
android:textColor="@drawable/text_colors_selector"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Основное извращение заключалось в том, что TabHost во всех примерах фигурирует как родительский тег по отношению ко всем остальным, а перенос TabWidget'а относительно FrameLayout'а давал нужный результат. С FragmentTabHost'ом пришлось поступить иначе и избавиться от TabWidget'a в итоге.
Добрый день, а вот если у меня много табов и я хочу чтобы они (табы) скролились. Как это сделать??
ОтветитьУдалитьДоброго времени суток! В стандартном режиме табы не скроллятся, если их много и они не помещаются на экране, то лучше делать таб - More (больше) с многоточием. Если нужен именно скролл - то лучше делать отдельным компонентом, например, унаследованным от FragmentTabHost
Удалить