如果计数器达到特定数字,如何在按钮上添加声音?

时间:2019-07-02 13:07:32

标签: java android-studio

我试图在计数器达到某个数字时用按钮发出声音,以便当我单击按钮并且计数器达到特定数字时播放声音。

public class MainActivity extends AppCompatActivity {

    int ScoreTeamA = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        displayForTeamA(0);
        final MediaPlayer beepsounds = MediaPlayer.create(this, R.raw.beepsound);
        Button playbeepsound = (Button) this.findViewById(R.id.three_points);

        playbeepsound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                beepsounds.start();
            }
        });

    }

    public void displayForTeamA(int score) {
        TextView scoreView = (TextView) findViewById(R.id.team_a_score);
        scoreView.setText(String.valueOf(score));
    }

    public void threepoints(View v) {
        ScoreTeamA += 1;
        displayForTeamA(ScoreTeamA);

        if (ScoreTeamA == 33) {      
            ScoreTeamA = 0;
        }
    }

    public void resetscore(View v) {
        ScoreTeamA = 0;
        displayForTeamA(0);
    }
}

使用此代码,我有声音,但计数器保持为零。

1 个答案:

答案 0 :(得分:0)

您在OnClickListener上犯了一个错误,因为它只播放声音。现在,我已经完成了该方法的调用,一旦计数达到 33 ,声音就会播放,并且ScoreTeamA设置为零。我想这就是您要实现的

public class MainActivity extends AppCompatActivity {

int ScoreTeamA = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    displayForTeamA(0);
    final MediaPlayer beepsounds = MediaPlayer.create(this, R.raw.beepsound);
    Button playbeepsound = (Button) this.findViewById(R.id.three_points);

    playbeepsound.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            threepoints(v);
        }
    });

}

public void displayForTeamA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
}

public void threepoints(View v) {
    ScoreTeamA += 1;
    displayForTeamA(ScoreTeamA);

    if (ScoreTeamA == 33) {      
        ScoreTeamA = 0;
        beepsounds.start();
    }
}

public void resetscore(View v) {
    ScoreTeamA = 0;
    displayForTeamA(0);
}

}