java - 如何使用复选框将应用程序静音/取消静音

标签 java android audio checkbox sharedpreferences

我编写了一个测验,现在我设置为,当未选中主 Activity 对话框 2 中的复选框 (checkboxmp) 时,媒体播放器 mp/mp2 的音量将设置为 (1,1)。如果选中该复选框,声音将被静音。问题是复选框的选择不会被保存。例如,当我选中复选框并切换到 Activity 2 然后再切换回来时,复选框的选择将不会保存。我如何设置,如果用户在整个 Activity 中勾选复选框,则复选框会被勾选,并且在应用程序重新启动时也会被勾选。感谢您的浏览!

主要 Activity :

             public class QuizActivity extends AppCompatActivity {

private ActionBarDrawerToggle mToggle;

private QuestionLibrary mQuestionLibrary = new QuestionLibrary();

private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
Dialog dialog;
Dialog dialog2;
TextView closeButton;
TextView closeButton2;
CheckBox checkBoxmp;


SharedPreferences mypref;
SharedPreferences.Editor editor;

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

    final MediaPlayer mp = new MediaPlayer();
    final MediaPlayer mp2 = MediaPlayer.create(this,R.raw.wrong);







    //Dialog 1
    createDialog();
    Button dialogButton = (Button) findViewById(R.id.dialogbtn);
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.show();

        }
    });

    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    //end Dialog 1

    //Dialog 2
    createDialog2();
    Button dialogButton2 = (Button) findViewById(R.id.dialogbtn2);
    dialogButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog2.show();

        }
    });


    closeButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog2.dismiss();
        }
    });
    //end Dialog 2

    SharedPreferences mypref = getPreferences(MODE_PRIVATE);

    final SharedPreferences.Editor editor = mypref.edit();

    checkBoxmp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                                @Override
                                                public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                                                    editor.putBoolean("playSounds", !isChecked);
                                                    editor.commit();
                                                    if (!isChecked){
                                                        mp.setVolume(1,1);
                                                        mp2.setVolume(1,1);
                                                    }else{
                                                        mp.setVolume(0,0);
                                                        mp2.setVolume(0,0);
                                                    }
                                                }
                                            })
    ;


   /* boolean playSounds = mypref.getBoolean("playSounds", false);
    /checkBoxmp.setChecked(!playSounds);
    if(playSounds){

        mp.setVolume(1,1);
        mp2.setVolume(1,0);
    }
    else{

        mp.setVolume(0,0);
        mp2.setVolume(0,0);
    }*/





    TextView shareTextView = (TextView) findViewById(R.id.share);
    shareTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(Intent.ACTION_SEND);
            myIntent.setType("text/plain");
            myIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello!");
            myIntent.putExtra(Intent.EXTRA_TEXT, "My highscore in Quizzi is very high! I bet you can't beat me except you are cleverer than me. Download the app now! https://play.google.com/store/apps/details?id=amapps.impossiblequiz");
            startActivity(Intent.createChooser(myIntent, "Share with:"));
        }
    });

    mQuestionLibrary.shuffle();


    setSupportActionBar((Toolbar) findViewById(R.id.nav_action));
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Able to see the Navigation Burger "Button"

    ((NavigationView) findViewById(R.id.nv1)).setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.nav_stats:
                    startActivity(new Intent(QuizActivity.this, Menu2.class));
                    break;
                case R.id.nav_about:
                    startActivity(new Intent(QuizActivity.this, Menu3.class));
                    break;
            }

            return true;
        }
    });

    mScoreView = (TextView) findViewById(R.id.score_score);
    mQuestionView = (TextView) findViewById(R.id.question);
    mButtonChoice1 = (Button) findViewById(R.id.choice1);
    mButtonChoice2 = (Button) findViewById(R.id.choice2);
    mButtonChoice3 = (Button) findViewById(R.id.choice3);

    final List<Button> choices = new ArrayList<>();
    choices.add(mButtonChoice1);
    choices.add(mButtonChoice2);
    choices.add(mButtonChoice3);

    updateQuestion();



    for (final Button choice : choices) {
        choice.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (choice.getText().equals(mAnswer)) {


                    try {
                        mp.reset();
                        AssetFileDescriptor afd;
                        afd = getAssets().openFd("sample.mp3");
                        mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                        mp.prepare();
                        mp.start();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    updateScore();
                    updateQuestion();
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();



                } else {
                    mp2.start();
                    Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score", mScore); // pass score to Menu2
                    startActivity(intent);
                }
            }
        });
    }

}

private void updateQuestion() {
    if (mQuestionNumber < mQuestionLibrary.getLength()) {
        mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
        mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
        mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));
        mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber++);
    } else {
        Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(QuizActivity.this, Menu2.class);
        intent.putExtra("score", mScore);
        startActivity(intent);
    }
}

private void updateScore() {
    mScoreView.setText(String.valueOf(++mScore));

    SharedPreferences mypref = getPreferences(MODE_PRIVATE);
    int highScore = mypref.getInt("highScore", 0);

    if (mScore > highScore) {
        SharedPreferences.Editor editor = mypref.edit();
        editor.putInt("highScore", mScore);
        editor.apply();
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return mToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

private void createDialog() {
    dialog = new Dialog(this);
    dialog.setTitle("Tutorial");
    dialog.setContentView(R.layout.popup_menu1_1);
    closeButton = (TextView) dialog.findViewById(R.id.closeTXT);
}


private void createDialog2() {
    dialog2 = new Dialog(this);
    dialog2.setTitle("Settings");
    dialog2.setContentView(R.layout.popup_menu1_2);
    closeButton2 = (TextView) dialog2.findViewById(R.id.closeTXT2);
    checkBoxmp = (CheckBox) dialog2.findViewById(R.id.ckeckBox);


}

}

最佳答案

您可以使用SharedPreferences存储用户设置:

SharedPreferences.Editor editor = mypref.edit();
//..
yourCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {   
       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
           editor.putBoolean("playSounds", isChecked);
           editor.commit();
       }
   }
);   

然后,当您必须播放声音时,请检查用户设置:

SharedPreferences mypref = getPreferences(MODE_PRIVATE);
boolean playSounds = mypref.getBoolean("playSounds", false);

if(playSounds){
   mp.start();
}

关于java - 如何使用复选框将应用程序静音/取消静音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45631120/

相关文章:

java - 想要播放应用程序的背景音乐时,计算机找不到 'AudioStream'

java - 如何使用 Java 递归打印(但不返回)字符串?

android - 触摸 SwitchCompat 小部件不会更改 SwitchPreference 值

java - 无法让 ActionBar 在 Android 项目中工作并且 Android ActionBar 示例有很多编译错误

c# - 使用 Xamarin 表单录制和播放音频

cordova - 捕获音频媒体Phonegap错误代码3

java - 如果 hashCode() 没有被覆盖,HashSet 允许重复项插入

java - 在 Spring Tool Suite 3.6.1 上安装 Groovy 1.8

java - Struts 2 中某些 Struts 1 方法的替代方案

安卓布局 : Wrap two textview