我已尝试在网络上提供每个单一解决方案,但无法使其正常运行。
请帮我指出我在ViewPager
适配器实施中的错误,错误'无法解决方法getResources()
'不断出现!
以下是相关课程的代码(getPageTitle
方法中的问题):
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
@Override
public Fragment getItem(int position) {
if(position == 0)
{
Tab1 tab1 = new Tab1();
return tab1;
}
else
{
Tab2 tab2 = new Tab2();
return tab2;
}
}
private int[] imageResId = {
R.drawable.social,
R.drawable.artist
};
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
// return tabTitles[position];
Drawable image = getResources().getDrawable(imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
@Override
public int getCount() {
return NumbOfTabs;
}

答案 0 :(得分:0)
你不能像上面的类中那样调用getResources()方法。 将上下文发送到适配器,如
private Context mContext;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb, Context context) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
this.mContext = context
}
然后调用mContext.getResources();像
Drawable image = mContext.getResources().getDrawable(imageResId[position]);
答案 1 :(得分:0)
在构造函数中将Context对象传递给ViewPagerAdapter,并且:
传递Context对象:
Context my_context ;
public ViewPagerAdapter(Context passed_context ,FragmentManager fm ... )
{
this.my_context = passed_context ;
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
然后你可以通过
获得这个功能my_context.getResources() ;