如何在Android中持久更改TextView文本?

时间:2016-06-13 07:25:17

标签: android android-studio-2.0

我尝试过使用Thread,但是不成功,在使用EditText作为输入更改TextView文本后,textView没有更改。请帮帮我!

        Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            //shared is SharedPreferences object that I define as an instance variable
            String inp = shared.getString("input", def);

            textView.setText(inp);
            Log.d("input",inp);
    });

    thread.start();

2 个答案:

答案 0 :(得分:0)

为什么要在单独的线程中执行此操作。即使您愿意,也无法在非UI线程中更新任何UI组件,例如textView。

答案 1 :(得分:0)

试试这个:

    Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        //shared is SharedPreferences object that I define as an instance variable
        String inp = shared.getString("input", def);
         runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        textView.setText(inp);
                        Log.d("input",inp);
                    }
                });
});

thread.start();

要更新UI,您应该使用主ui线程。看看:

Android runOnUiThread explanation