Java 如何解决(上下文:此)
我(在这方面)有问题。无法应用错误ImageView。我在fragment类中编写这段代码Java 如何解决(上下文:此),java,android,Java,Android,我(在这方面)有问题。无法应用错误ImageView。我在fragment类中编写这段代码 ViewFlipper v_flipper; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.
ViewFlipper v_flipper;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
int images[] = {R.drawable.promo1, R.drawable.promo2, R.drawable.promo3};
v_flipper = rootView.findViewById(R.id.v_flipper);
for(int image: images){
flipperImages(image);
}
return rootView;
}
public void flipperImages(int image){
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(image);
v_flipper.addView(imageView);
v_flipper.setFlipInterval(4000);
v_flipper.setAutoStart(true);
v_flipper.setInAnimation(this, android.R.anim.slide_in_left);
v_flipper.setOutAnimation(this, android.R.anim.slide_out_right);
}
从rootview调用,使用该函数作为fragment的返回值。可能是在此行中传递了
this
,但该方法不在正确的上下文中:
ImageView imageView = new ImageView(this);
要在片段中执行此操作,首先需要使用getContext()
获取它所属的上下文:
但是,如果没有更多的信息,我无法为您提供更多帮助。在片段中使用getActivity()Like
您问题中的此
指的是类片段
,其中您需要上下文
的实例(它是活动
的父级)
你可以用
newimageview(getActivity())代码>
或
newimageview(getContext())
从哪里调用FlipperImage
方法?我们需要更多的代码如果您在一个片段中,请使用“newImageView(getContext())”。。。请记住getContext()可以返回null。。。所以,最好是对照检查null@W0rmH0le非常感谢!!!
ImageView imageView = new ImageView(getContext());
ImageView imageView = new ImageView(getActivity());