简体   繁体   中英

I don't know how to implement interfaces in Java

I have problems with opening an activity, I know that I have to implement interfaces to these interfaces of OnClickListener , OnInitListener . I have tried with @Override . In my android studio it says that I have to implement an abstract on onclick() method in onclicklistener . I am a newbie in programing so any help is much appreciated!

public void addGlossary(View v){
    Intent intent = new Intent (this, addGlossary.class);
    Button buttonZero = (Button) findViewById(R.id.buttonZero);
    startActivity(intent);

}

Here is the code for the activity:

public class addGlossary extends Activity implements OnClickListener, OnInitListener {


    private int MY_DATA_CHECK_CODE = 0;


    private TextToSpeech myTTS;


    private MediaPlayer mMediaPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_glossary);


        Button speakButton = (Button)findViewById(R.id.speak);
        speakButton.setOnClickListener(this);


        Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer = MediaPlayer.create(this, R.raw.button);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.start();
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mMediaPlayer.stop();
            }
        });

When I have implemented those interfaces, and I try to connect to the activity my phone says that the application has stopped. I do not know what the problem is. Any help is appreciated.

What I implemented: onInit was already done

@Override

public void onClick(View v){
Button speakButton = (Button)findViewById(R.id.speak);
speakButton.setOnClickListener(this);

}

You must implement all the abstract methods in addGlossary , add following code to the class,

1) onClick for OnClickListener

@Override
public void onClick (View v) {
    //do someting when the view clicked
}

2) onInit for OnInitListener

@Override
public void onInit (int status) {
    //do someting when tts onInit
}

Click here to learn more about Java Interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM