复选框无法激活或停用android中的声音

时间:2016-05-11 22:32:44

标签: android android-mediaplayer android-checkbox android-toast

在我的简单的游戏应用程序中,我使用复选框激活或停用声音,但是当我在模拟器中运行应用程序并在复选框上取消停用不起作用并且音乐仍然打开时,任何帮助表示赞赏

    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.widget.CheckBox;
   import android.widget.Toast;

    public class Setting extends Activity {
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting);

   }
public static MediaPlayer Sounds;

private CheckBox sound;
private Boolean isChecked = false;

public void Is_checked() {
    if (isChecked) {

        Sounds.start();

        Toast.makeText(this, "Sound is activated ",
                Toast.LENGTH_LONG).show();
    }

    else {
        Sounds.stop();
        Sounds = MediaPlayer.create(this, R.raw.preview);

        Toast.makeText(this, "Sound is deactivated ",
                Toast.LENGTH_LONG).show();
    }
}}

XML CODE

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CD853F" >

<CheckBox
    android:id="@+id/sound"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="78dp"
    android:layout_marginTop="86dp" />

<TextView
    android:id="@+id/soundt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/sound"
    android:layout_alignBottom="@+id/sound"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="64dp"
    android:text="@string/text10_view"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#000000" />

1 个答案:

答案 0 :(得分:0)

试试这段代码:

 CheckBox sound = (CheckBox) findViewById(R.id.sound);
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                Sounds.start();
                Toast.makeText(this, "Sound is activated ",
                        Toast.LENGTH_LONG).show();
            } else {
                Sounds.stop();
                Sounds = MediaPlayer.create(this, R.raw.preview);
                Toast.makeText(this, "Sound is deactivated ",
                        Toast.LENGTH_LONG).show();
            }
        }
    });