FragmentStatePagerAdapter中的getResources()?

时间:2016-05-06 19:32:19

标签: android

当我尝试使用getResources().getDrawable(icons[position])时,它说“无法解析方法getResources()”,提供了创建getter,create属性或create方法的选项。

为什么我不能从这个课程中调用getResources()

import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import java.util.List;



    public class MeinPageAdapter extends FragmentStatePagerAdapter {

        private final List<Fragment> fragments; 
        private CharSequence Titles[];

        int icons [] = {R.drawable.ic_info, R.drawable.ic_home,         R.drawable.ic_settings};
    Drawable drawable;

    public MeinPageAdapter(FragmentManager fm, List<Fragment> fragments,       CharSequence[] titles) {
        super(fm);
        this.fragments = fragments;
        this.Titles = titles;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        drawable = getResources().getDrawable(icons[position]);

        return Titles[position];
    }

    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }


}

1 个答案:

答案 0 :(得分:2)

那是因为getResources() is a method of class Context,但你在FragmentStatePagerAdapter中,并没有扩展上下文。

一个可能的解决方案(在我看来最好的)是在你的适配器的构造函数中传递一个Context:

private Context context;

public MeinPageAdapter(FragmentManager fm, List<Fragment> fragments,       CharSequence[] titles, Context context) {
    super(fm);
    this.fragments = fragments;
    this.Titles = titles;
    this.context = context;
}

@Override
public CharSequence getPageTitle(int position) {
    drawable = context.getResources().getDrawable(icons[position]);

    return Titles[position];
}

由于您在Activity中创建了适配器的实例,因此在创建适配器时可以传递this

MeinPageAdapter adapter = new MeinPageAdapter(/* your other params*/, this);