Search code examples
javaandroidandroid-event

Android:OnClick Event not functioning


I have imageView for play and stop and I have tried to implement OnClickListener. But the click event is not handled. Even if I try to start the application in debug mode then also I am not able to detect click event. What could be the error in this code ?

public class DetailActivity extends ActionBarActivity implements
        OnClickListener {

    MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_activity);
        try {
            mp = MediaPlayer.create(this, R.raw.baabaa);
            mp.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.stop:
            mp.stop();
            break;
        case R.id.play:
            mp.start();
            break;

        default:
            break;
        }
    }

}

Solution

  • U haven't stated the ImageView in the activity for example

    ImageView img = (ImageView)findViewById(R.id.XXX);
    img.setOnClickListener(this);
    

    Then the onClick will work.

    If you have asssigned through XML please check the names properly For XML Check this

    <ImageView android:id="@+id/play"
    android:layout_width="wrap_content" android:layout_height="wrap_content"    android:layout_gravity="center"
    android:contentDescription="playButton" 
    android:src="@drawable/play_btn"
    android:onClick="myMethod" />
    

    Check this link It contains really good inforamtion