我在实现自定义标签时遇到问题,我知道我可以在我的布局文件中仅使用public class TabsAdapter extends FragmentPagerAdapter {
private int mPageCount;
private Context mContext;
private int[] stringResID = { R.string.serverString, R.string.localString, R.string.commonString, R.string.searchString };
private int[] imagesResID = { R.drawable.tab1, R.drawable.tab2, R.drawable.tab3, R.drawable.tab4};
public TabsAdapter(FragmentManager fm, int pageCount, Context context) {
super(fm);
mPageCount = pageCount;
mContext = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab, null);
TextView tv = (TextView) view.findViewById(R.id.titleTab);
tv.setText(stringResID[position]);
ImageView img = (ImageView) view.findViewById(R.id.tabImage);
img.setImageDrawable(ContextCompat.getDrawable(mContext, imagesResID[position]));
return view;
}
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return mPageCount;
}
}
作为TextView,但我需要在一个布局文件中显示另外两个ImageView。我有一个自定义布局,我这样膨胀:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/titleTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ololo"
android:layout_centerInParent="true"/>
<ImageView
android:id="@+id/tabImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_above="@+id/titleTab"/>
</RelativeLayout>
我的布局文件:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
TabsAdapter pagerAdapter =
new TabsAdapter(getSupportFragmentManager(), 4,MainActivity.this);
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if(tab != null) {
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
并从MainActivity中调用它:
{{1}}
所以问题是:我做错了什么? Becaus这段代码只是在标签中给我文字,没有ImageView。如果您尝试这样做,请提供帮助。