只想举例说明正确和接受的答案。:)
首先,在将适配器添加到 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
并且正在将图像设置到该位置,以便完全显示实际的字符串。