我正在android studio中创建一个钢琴应用程序:
我的播放按钮有一个点击监听器,当按下该按钮时,应该使录制和播放按钮不可见,并且在录制的声音播放时可以看到停止按钮。
播放按钮
uri = new URI( type, params , null );
URL url = uri.toURL();
HttpURLConnection conn;
conn= (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
System.out.println(" The Response Code after Sending the SMS : "+responseCode);
InputStream isr = ((responseCode>= 200)&&(responseCode< 300)) ? conn.getInputStream() : conn.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isr));
String line;
StringBuilder result = new StringBuilder("");
while((line = rd.readLine()) != null)
{
result.append(line);
}
String response = result.toString();
System.out.println("The Response after Sending the SMS : "+response);
切换按钮可见性的方法
mBtn_Play.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mRecordingState = "Playing";
switchButtonVisibility();
for (final int sound: mListRecordedSounds )
{
if (mRecordingState == "Ready")
{//break out of loop when stop button is pressed
break;
}
else {
mSoundPool.play(sound, 1,1,1,0,1);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
});
}
使用录制和停止按钮,这可以正常工作
private void switchButtonVisibility()
{
if (mRecordingState != "Ready")
{
mBtn_Stop.setVisibility(View.VISIBLE);
mBtn_Record.setVisibility(View.GONE);
mBtn_Play.setVisibility(View.GONE);
}
else
{
mBtn_Stop.setVisibility(View.GONE);
mBtn_Record.setVisibility(View.VISIBLE);
mBtn_Play.setVisibility(View.VISIBLE);
}
}
由于一些奇怪的原因,它首先执行mBtn_Record.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mListRecordedSounds.clear();
mRecordingState = "Recording";
switchButtonVisibility();
}
});
mBtn_Stop.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mRecordingState = "Ready";
switchButtonVisibility();
}
});
循环并在for
方法更改哪些按钮可见之前播放声音。这似乎没有任何意义,因为该方法在循环之上。有没有办法设置它,以便按钮可见性在之前更改
执行循环并播放声音?
答案 0 :(得分:1)
延迟执行,在视图上发布事件。这将确保在视图更新后立即执行操作:
@Override
public void onClick(View v) {
mRecordingState = "Playing";
switchButtonVisibility();
mBtn_Play.post(new Runnable() {
@Override
public void run() {
for (final int sound : mListRecordedSounds ) {
// play the sound here
...
}
}
});
}