两个按钮与onClick在同一个地方

时间:2015-05-20 09:07:27

标签: android android-xml

我需要在onClick上做两个按钮。这两个按钮必须位于同一个地方。一个按钮用于启动语音记录onClick的功能,另一个按钮用于停止功能onClick.is它可能吗?如果我得到任何建议,对我有帮助。谢谢。

我搜索了许多SO帖子和教程。我没有得到它。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

public class MyActivity extends Activity {
     Button buttonStart;
     Button buttonStop;

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         buttonStart = (Button) findViewById(R.id.buttonStart);
         buttonStop = (Button) findViewById(R.id.buttonStop);
         buttonStart.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
                 //for example mediaPlayer.start(); if you have a media player
             }
         });
         buttonStop.setOnClickListener(new View.OnClickListener(){
             public void onClick(View v){
                 //do what you want - for example mediaPlayer.stop();
             }
         });
    }
}

评论之后:然后使用一个按钮并检查它是否正在录制,例如:

public class MyActivity extends Activity {
     Button button;
     boolean isRecording = false;

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         button = (Button) findViewById(R.id.myButton);
         button.setText("Start");
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
                 if(isRecording == fasle){
                     //start recording
                     isRecording = true; //set the variable to know that it is recording
                     button.setText("Stop");
                 } else {
                     //stop recording
                     isRecording = false; //set the variable to know that it is not recording
                     button.setText("Start");
                 }
             }
         });
    }
}

答案 1 :(得分:0)

如果您想要完全相同(即2个按钮)

您可以使用relativelayout,并在其中添加两个按钮。

您可以通过编程方式显示/隐藏它们,如:

public void onClick(View v) 
    {
      switch(v.getId()) {
      case R.id.btn1:
       btn1.setVisibility(View.GONE);
       btn2.setVisibility(View.VISIBLE);
     break;

    case R.id.btn2:
     btn2.setVisibility(View.GONE);
     btn1.setVisibility(View.VISIBLE);
    break;
   }
 }

否则, you can even use one button for both the functionalities (start and stop) 为 -

    public void onClick(View v) 
   {
    if(btn1.getText().toString().equalsIgnoreCase("start"))
    {
        btn1.setText("stop");
        mp2.start();
        musicPlaying = true;
    }
    else if(btn1.getText().toString().equalsIgnoreCase("stop"))
    {
        btn1.setText("start");
        mp2.stop();
        musicPlaying = false;
    }
}