gpt4 book ai didi

java - Android:简单线程示例崩溃

转载 作者:行者123 更新时间:2023-11-29 19:19:17 25 4
gpt4 key购买 nike

我正在尝试了解 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.

最佳答案

您需要使用处理程序来处理 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();
}
});
}

}

关于java - Android:简单线程示例崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com