Click Button – play sound

Click Button – play sound Example in Android

MainCLASS

package com.example.malik.test;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button button1, button2;
private TextView textView;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mp = MediaPlayer.create(this, R.raw.btn1);

button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);

button1.setOnClickListener(this);
button2.setOnClickListener(this);
textView.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
mp.start();
break;

case R.id.button2:
mp.start();
break;

case R.id.textView:
mp.start();
break;
}
}
}

 

MainXML

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:orientation=”horizontal”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.example.malik.test.MainActivity”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Button 1″
android:id=”@+id/button1″
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”39dp” />

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Buton 2″
android:id=”@+id/button2″
android:layout_below=”@+id/button1″
android:layout_centerHorizontal=”true”
android:layout_marginTop=”48dp” />

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceLarge”
android:text=”Hello malik”
android:id=”@+id/textView”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true” />
</RelativeLayout>

 

Output :

pic

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.