3

我正在开发一个 Android 应用程序,我需要制作一个按钮,该按钮将成为 Android 服务播放和停止的播放/停止按钮。

  • 播放按钮用于startActivity();

  • 停止按钮用于stopActivity();

我怎么做这个?

4

3 回答 3

2

您只需要声明一个标志变量并根据这样的标志值声明 onclick() 的主体。

public class ServiceActivity extends Activity {
    Button play;
    int button_status=1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        play=(Button)findViewById(R.id.button1);

        play.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(button_status == 1)//play the service
                {
                button_status=0;
                Intent i=new Intent(ServiceActivity.this,Playing.class);
                startService(i);
                }
                else//stop the service
                {
                button_status=1;
                Intent i=new Intent(ServiceActivity.this,Playing.class);
                stopService(i); 
                } 
        });

    }  
}

或者您可以使用ToggleButton来满足您的需求。

于 2013-06-27T13:16:08.273 回答
1

Just use a boolean to remember if it's on or off and toggle it

boolean isOn = false;

public void startStopButton() {
    if(isOn) {
        stopActivity();
        isOn = false;
    } else {
        startActivity();
        isOn = true;
    }
}

Now whenever your button is pressed, you can call this method.

于 2013-06-27T12:52:05.033 回答
1
boolean isStop = false;

public void startorStop() {
    if(isStop) {
      // play  it
    } else {
      //stop it  
    }
isStop = !isStop;
}
于 2013-06-27T13:00:57.857 回答