Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何解决(上下文:此)_Java_Android - Fatal编程技术网

Java 如何解决(上下文:此)

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.

我(在这方面)有问题。无法应用错误ImageView。我在fragment类中编写这段代码

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());