我正在创建一个应用程序,当按下按钮时,它会在“for 循环”中生成一些啁啾声,我想在循环期间阻止按钮,并在循环结束时释放它们。
我试过这个,但应用程序崩溃:
package android.nacho.UltraSoundSender;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class UltraSoundSender extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ultra_sound_sender);
Button btnCode = (Button) findViewById(R.id.btnCode);
btnCode.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View arg0) {
enableButton(false);
new Thread( new Runnable( )
{
public void run( )
{
//working=false;
// int Code=Integer.parseInt(((EditText)findViewById(R.id.Code)).getText().toString());
//((EditText)findViewById(R.id.Code)).setText("");
String word= ((EditText)findViewById(R.id.Code)).getText().toString();
Integer digits[]= new Integer[64];
int NumChar= word.length();
//This split the string in chars
for(int i = 0; i < NumChar ; i++){
digits[i]=(int)word.charAt(i);
}
//Values of the chirp
int startFreq = 3000;
int endFreq = 7000;
double impulseDuration = 50;
for(int IndexChar= 0; IndexChar< NumChar ; IndexChar++)
{
new ChirpGenerator().playDOWN(startFreq, endFreq, impulseDuration, digits[IndexChar]);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
enableButton(true);
}
} ).start();
}
});
}
//Enable/disable button
private void enableButton(boolean isEnable)
{
((Button)findViewById(R.id.btnCode)).setEnabled(isEnable);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ultra_sound_sender, menu);
return true;
}
}
我在 logcat 中收到此错误:
06-19 11:15:00.852: E/AndroidRuntime(29419): 致命异常: Thread-5516 06-19 11:15:00.852: E/AndroidRuntime(29419): android.view.ViewRootImpl$CalledFromWrongThreadException: 只有原始线程创建视图层次结构的可以触摸其视图。06-19 11:15:00.852: E/AndroidRuntime(29419): 在 android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746) 06-19 11:15:00.852: E/AndroidRuntime(29419): 在 android. view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:854) 06-19 11:15:00.852: E/AndroidRuntime(29419): 在 android.view.ViewGroup.invalidateChild(ViewGroup.java:4077) 06-19 11:15: 00.852: E/AndroidRuntime(29419): 在 android.view.View.invalidate(View.java:10322) 06-19 11:15:00.852: E/AndroidRuntime(29419): 在 android.widget.TextView.invalidateDrawable(TextView .java:4601) 06-19 11:15:00.852:
我应该在哪里调用启用功能?我猜出线程但是如何?