错误:无法执行android:onClick的方法

问题描述

我在Google documentation page上找到了此代码(Android Studio自动对其进行了一些更改):

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static void ssmlToAudio(String ssmlText,String outFile) throws Exception {
    // Instantiates a client
    try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
        // Set the ssml text input to synthesize
        SynthesisInput input = SynthesisInput.newBuilder().setSsml(ssmlText).build();

        // Build the voice request,select the language code ("en-US") and
        // the ssml voice gender ("male")
        VoiceSelectionParams voice =
                VoiceSelectionParams.newBuilder()
                        .setLanguageCode("en-US")
                        .setSsmlGender(SsmlVoiceGender.MALE)
                        .build();

        // Select the audio file type
        AudioConfig audioConfig =
                AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();

        // Perform the text-to-speech request on the text input with the selected voice parameters and
        // audio file type
        SynthesizeSpeechResponse response =
                textToSpeechClient.synthesizeSpeech(input,voice,audioConfig);

        // Get the audio contents from the response
        ByteString audioContents = response.getAudioContent();

        // Write the response to the output file
        try (OutputStream out = new FileOutputStream(outFile)) {
            out.write(audioContents.toByteArray());
            System.out.println("Audio content written to file " + outFile);
        }
    }
}

我想在click事件上运行此方法。所以这是我到目前为止尝试过的:

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void onClick(View view) throws Exception {
    ssmlToAudio("Hello","test");
}

但是,如果我运行我的应用程序并单击一个按钮,则会收到此错误

java.lang.IllegalStateException:无法执行以下方法 android:onClick

我在做什么错了?

解决方法

您必须在活动中实现onClickListener,然后重写onClick方法。