尝试在空 object 引用上调用虚拟方法 'int android.view.MotionEvent.getAction()'

Attempt to invoke virtual method 'int android.view.MotionEvent.getAction()' on a null object reference

我正在尝试捕获用户的任何 Touch 事件以将其用于布尔验证(如 "press on the screen to continue")。但我收到一个错误,这是问题标题。 上面写着:

resultadoPalavra.setText("Você acertou! Pressione na tela para continuar");

就是我提到的"press on the screen continue"。

代码:

public class ApurarResultadoFragment extends Fragment{

private TextView resultadoPalavra;
String palavraDigitada;
String resposta;
MainActivity mActivity = new MainActivity();
private boolean isTouch = false;
MotionEvent event;


public ApurarResultadoFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_apurar_resultado, container, false);
    resultadoPalavra = (TextView) view.findViewById(R.id.TextViewTesteFragment);
    palavraDigitada = this.getArguments().getString("oqSeraFalado");
    resposta = this.getArguments().getString("resposta");

    if(testeResultado()){
        resultadoPalavra.setText("Você acertou! Pressione na tela para continuar");
        if(onTouchEvent(view, event)){
            Log.v("teste","" + isTouch);
        }

    }
    return view;
}

public boolean onTouchEvent(View v, MotionEvent event){
    int eventaction = event.getAction();
    switch (eventaction){
        case MotionEvent.ACTION_DOWN:
            isTouch = true;
            break;
        case MotionEvent.ACTION_UP:
            isTouch = true;
            break;
        case MotionEvent.ACTION_MOVE:
            isTouch = true;
            break;
    }
    return true;
}

public boolean testeResultado() {
    if (resposta.equalsIgnoreCase(palavraDigitada)){
        return true;
    }else{
        return false;
    }
}
}

如何初始化变量 "event"?我想她就是问题所在

以下是将 TouchListener 添加到视图的方法:

view.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        int eventaction = event.getAction();
        switch (eventaction) {
            case MotionEvent.ACTION_DOWN:
                isTouch = true;
                break;
            case MotionEvent.ACTION_UP:
                isTouch = true;
                break;
            case MotionEvent.ACTION_MOVE:
                isTouch = true;
                break;
        }
        return true;
        }
    });

但在你的情况下,我会改用 OnClickListener:

view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.v("teste", "touched");
    }
});