我尝试了很多方法来解决这个问题,但不幸的是,未能找到解决方案。这是我呼叫寻呼机适配器的主要活动:
@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);
}
}
在方法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
正在获取null。
&对于getCount
方法,使用类似:
@Override
public int getCount() {
return mcontext.getResources().getString(R.string.headng1).length;
}
您在这里使用声明时间的上下文
public String[] slide_description={
mcontext.getString(R.string.string1),
};
这就是为什么它是null的原因。