只是想給出正確和被接受的答案的例子。 :)
首先,添加選項卡並在將適配器添加到viewpager時設置其自定義視圖。例如看到下面幾行:
mViewpager = (ViewPager) view.findViewById(R.id.pager);
//Do something with your view before setting up adapter
ViewPager.setAdapter(mSectionsPagerAdapter);
mSlidingTabLayout = (SlidingTabLayout) View().findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setCustomTabView(R.layout.custom_tab_title, R.id.tabtext);
mSlidingTabLayout.setViewPager(mViewPager);
哪裏sliding_tabs
是要添加的tabs_titles和xml
文件中定義的viewpager
,如:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.packagename.SlidingTabLayout
android:id="@+id/sliding_tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/sliding_tabs"
tools:context=".ActivityUser"
android:fitsSystemWindows="true"
android:textStyle="bold"
android:textSize="20dp"/>
</RelativeLayout>
,並在那裏custom_tab_title
是一個獨立的xml
文件在您layout
例如:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/titletab">
<ImageView
android:id="@+id/tabimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="2dp"
/>
<TextView
android:id="@+id/tabtext"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="bottom"
android:paddingBottom="15dp"
android:paddingLeft="4dp"
android:paddingRight="4dp"/>
</LinearLayout>
和你可以通過設置圖像爲特定標籤:
Drawable tab_image = getResources().getDrawable(getResources().getIdentifier("image_name_in_drawable", "drawable", "com.packagename"));
tab_image.setBounds(0, 0, 40, 40); //Setting up the resolution for image
ImageSpan imageSpanresource = new ImageSpan(tab_image);
//Notice the additional space at the end of the String
resourcesstring = "Tab1 ";
//here we are setting up the position to display image..
SpannableString viewpager_tab_title = new SpannableString(resourcesstring);
viewpager_tab_title.setSpan(imageSpanresource, resourcesstring.length()-1, resourcesstring.length(), 0);
通知,我已經加入到viewpager_tab_title
額外的空間和我的圖像設置到該位置,從而使實際的字符串被完全顯示。
http://stackoverflow.com/questions/28125794/slidingtablayout-with-icons-only – Daniel
我需要它,所以我改變了SlidingTabLayout代碼的一點點,以使它易於使用圖標的標籤https:// github。 com/kimkevin/SlidingIconTabLayout – kimkevin