1

我试图找出工作线程是如何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.
4

2 回答 2

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();
               }
            });
        }

    }
于 2017-03-13T10:15:58.410 回答
0

您不能从非 UI 线程执行 UI 工作。尝试像这样包装它:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
       Toast.makeText(getBaseContext(), "Your answer is correct!" , Toast.LENGTH_SHORT ).show();
    }
});

但是再想想它是否很好,你能不能为它写出更优雅的解决方案。

于 2017-03-13T10:16:58.533 回答