我正在获取'android.content.res.Resources android.content.Context.getResources()'

时间:2018-10-27 05:00:48

标签: android

我尝试了许多方法来解决问题,但不幸的是找不到解决方案。这是我从呼叫寻呼机适配器的主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);


    sliderAdapter = new _SliderAdapter(Activity.this);

    intro_view_pager = findViewById(R.id.intro_view_pager);
    intro_view_pager.setAdapter(sliderAdapter);





}

这是我的寻呼机适配器类。我正在尝试获取资源字符串,但上下文始终为空:

    static Context mcontext;
    LayoutInflater layoutInflater;

    public Wazu_SliderAdapter(Context context){
        this.mcontext =context;
    }


    @Override
    public int getCount() {
        return slide_headings.length;
    }


    public String[] slide_headings={



      mcontext.getResources().getString(R.string.headng1),

    };


    public String[] slide_description={

            mcontext.getString(R.string.string1),

    };

    public int[] slide_Images={

            R.drawable.image1,
            R.drawable.image2,

    };





    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==(RelativeLayout)object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        layoutInflater=(LayoutInflater) mcontext.getSystemService(mcontext.LAYOUT_INFLATER_SERVICE);

        View view=layoutInflater.inflate(R.layout.slider_layout,container,false);

        ImageView imageView=view.findViewById(R.id.intro_image);
        TextView heading_text=view.findViewById(R.id.intro_heading_textView);
        TextView description=view.findViewById(R.id.intro_textView_description);

        imageView.setImageResource(slide_Images[position]);
        heading_text.setText(slide_headings[position]);
        description.setText(slide_description[position]);

        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((RelativeLayout)object);

    }
}

1 个答案:

答案 0 :(得分:1)

代替方法 instantiateItem

中的这一行
layoutInflater=(LayoutInflater) mcontext.getSystemService(mcontext.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.slider_layout,container,false);

像这样使用

View view = LayoutInflater.from(container.getContext()).inflate(R.layout.slider_layout,container,false);

问题context通过了,而为空

&用于getCount方法,如:

@Override
public int getCount() {
    return mcontext.getResources().getString(R.string.headng1).length;
}

您在此处声明时使用上下文

public String[] slide_description={
    mcontext.getString(R.string.string1),
};

这就是为什么它为空的原因。