首页 > 解决方案 > How to combine two onClick for change text of Button and play/stop sound

问题描述

How to combine two functions in one button? How to make when button clicked - the button text change and sound will play

Now I can only play the sound or just change the button text

MainActivity.java

    public class MainActivity extends AppCompatActivity {
    Button one;

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


        final Button one = (Button) this.findViewById(R.id.button);

        one.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v) {
                String ButtonText=one.getText().toString();

                if(ButtonText.equals("Stop")){
                    one.setText("Play");

                }else {
                    one.setText("Stop");

                }
            }
        });

标签: javaandroid

解决方案


您似乎已经在onClick事件处理程序中更改了按钮文本。如果您正在使用某些方法调用来播放所需的声音,您也可以将其放入您的onClick处理程序方法中。例如:

public void onClick(View v) {
    String ButtonText=one.getText().toString();
    // method call that plays the sound
    if(ButtonText.equals("Stop")){
        one.setText("Play");
    } else {
        one.setText("Stop");
    }
}

推荐阅读