我试图了解Android Studio
中的工作线程是如何工作的。我创建了一个简单的例子,但我正在努力解决以下问题,java代码是:
package tlacitko.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view) {
new Thread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
}).start();
}
}
,xml代码为:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="7dp"
android:layout_marginTop="16dp"
android:onClick="sendMessage"
android:text="Ahoj"
app:layout_constraintLeft_toRightOf="@+id/editText"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
代码构建正常但在按钮后单击应用程序崩溃并出现以下错误:
Button has stopped.
答案 0 :(得分:2)
您需要使用处理程序来处理UI组件。您可以使用runOnUiThread(runnable)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view) {
runOnUiThread(new Runnable() {
@Override
public void run()
{
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
});
}
}
答案 1 :(得分:0)
您无法从非UI线程执行UI工作。 试着像这样包装:
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
}
});
但是再想一想它是不是很好,你能为它写出更优雅的解决方案。