如何在 Android TextView 中更改文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2300169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:19:04  来源:igfitidea点击:

how to change text in Android TextView

androidtextview

提问by user270811

I tried to do this

我试图这样做

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    t=new TextView(this); 

    t=(TextView)findViewById(R.id.TextView01); 
    t.setText("Step One: blast egg");

    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    t.setText("Step Two: fry egg");

but for some reason, only the second text shows up when I run it. I think it might have something to do with the Thread.sleep()method blocking. So can someone show me how to implement a timer "asynchronously"?

但出于某种原因,当我运行它时只显示第二个文本。我认为这可能与Thread.sleep()方法阻塞有关。那么有人可以告诉我如何“异步”实现计时器吗?

Thanks.

谢谢。

采纳答案by snctln

I just posted this answer in the android-discuss google group

我刚刚在 android-discuss google group 中发布了这个答案

If you are just trying to add text to the view so that it displays "Step One: blast egg Step Two: fry egg" Then consider using t.appendText("Step Two: fry egg");instead of t.setText("Step Two: fry egg");

如果您只是想在视图中添加文本以使其显示“第一步:炸鸡蛋第二步:煎鸡蛋”然后考虑使用t.appendText("Step Two: fry egg");代替t.setText("Step Two: fry egg");

If you want to completely change what is in the TextViewso that it says "Step One: blast egg" on startup and then it says "Step Two: fry egg" at a time later you can always use a

如果您想完全更改其中的内容,TextView以便在启动时显示“第一步:炸鸡蛋”,然后稍后显示“第二步:煎鸡蛋”,您可以随时使用

Runnable example sadboy gave

Sadboy 给出的可运行示例

Good luck

祝你好运

回答by Zordid

Your onCreate()method has several huge flaws:

你的onCreate()方法有几个巨大的缺陷:

1) onCreatepreparesyour Activity - so nothing that you do here will be made visibleto the user until this method finishes! For example - you will never be able to alter a TextView's text here more than ONEtime as only the last change will be drawn and thus visible to the user!

1)onCreate准备您的 Activity - 所以在此方法完成之前,您在此处所做的任何事情都不会对用户可见!例如-你将永远无法改变TextView这里的文本超过一周时间,只有最后的改动将被吸引,从而对用户可见!

2) Keep in mind that an Android program will - by default - run in ONEthread only! Thus: never use Thread.sleep()or Thread.wait()in your main thread which is responsible for your UI! (read "Keep your App Responsive"for further information!)

2) 请记住,Android 程序将 - 默认情况下 -仅在一个线程中运行!因此:永远不要在负责 UI 的主线程中使用Thread.sleep()Thread.wait()!(阅读“保持您的应用程序响应”以获取更多信息!)

What your initializationof your Activity does is:

您对 Activity的初始化是:

  • for no reason you create a new TextViewobject t!
  • you pick your layout's TextViewin the variable tlater.
  • you set the text of t(but keep in mind: it will be displayed only afteronCreate()finishes and the main event loop of your application runs!)
  • you wait for 10 secondswithin your onCreatemethod - this must never be doneas it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)
  • then you set another text - this one will be displayed as soon as your onCreate()method finishes and several other Activity lifecyclemethods have been processed!
  • 无缘无故地创建一个新TextView对象t
  • 您稍后TextView在变量中选择您的布局t
  • 您设置的文本t(但请记住:只有onCreate()完成并且应用程序的主事件循环运行才会显示!)
  • 您在您的方法中等待10 秒onCreate-绝不能这样做,因为它会停止所有 UI 活动并且肯定会强制 ANR(应用程序无响应,请参阅上面的链接!)
  • 然后你设置另一个文本 - 一旦你的onCreate()方法完成并且其他几个Activity 生命周期方法被处理,这个文本就会显示出来!

The solution:

解决方案:

  1. Set text only once in onCreate()- this must be the first text that should be visible.

  2. Create a Runnableand a Handler

    private final Runnable mUpdateUITimerTask = new Runnable() {
        public void run() {
            // do whatever you want to change here, like:
            t.setText("Second text to display!");
        }
    };
    private final Handler mHandler = new Handler();
    
  3. install this runnable as a handler, possible in onCreate()(but read my advice below):

    // run the mUpdateUITimerTask's run() method in 10 seconds from now
    mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
    
  1. 只设置一次文本onCreate()- 这必须是第一个应该可见的文本。

  2. 创建一个Runnable和一个Handler

    private final Runnable mUpdateUITimerTask = new Runnable() {
        public void run() {
            // do whatever you want to change here, like:
            t.setText("Second text to display!");
        }
    };
    private final Handler mHandler = new Handler();
    
  3. 将此 runnable 安装为处理程序,可能在onCreate()(但请阅读下面我的建议):

    // run the mUpdateUITimerTask's run() method in 10 seconds from now
    mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
    

Advice: be sure you know an Activity's lifecycle! If you do stuff like that in onCreate()this will only happen when your Activityis created the firsttime! Android will possibly keep your Activityalive for a longer period of time, even if it's not visible! When a user "starts" it again - and it is still existing - you will not see your first text anymore!

忠告:一定要知道 anActivity的生命周期!如果你做这样的事情onCreate()只会在你一次Activity创建时发生!Android 可能会让您存活更长时间,即使它不可见!当用户再次“启动”它时——它仍然存在——你将不会再看到你的第一个文本!Activity



=> Always install handlers in onResume()and disable them in onPause()! Otherwise you will get "updates" when your Activityis not visible at all! In your case, if you want to see your first text again when it is re-activated, you must set it in onResume(), not onCreate()!

=> 始终在onResume()其中安装处理程序并在其中禁用它们onPause()!否则,当您Activity根本不可见时,您将获得“更新” !在您的情况下,如果您想在重新激活时再次看到您的第一个文本,则必须将其设置为onResume(),而不是onCreate()

回答by Patrick Kafka

The first line of new text view is unnecessary

新文本视图的第一行是不必要的

t=new TextView(this); 

you can just do this

你可以这样做

TextView t = (TextView)findViewById(R.id.TextView01);

as far as a background thread that sleeps here is an example, but I think there is a timer that would be better for this. here is a link to a good example using a timer instead http://android-developers.blogspot.com/2007/11/stitch-in-time.html

至于在这里休眠的后台线程是一个例子,但我认为有一个计时器会更好。这是一个使用计时器的好例子的链接 http://android-developers.blogspot.com/2007/11/stitch-in-time.html

    Thread thr = new Thread(mTask);
    thr.start();
}

Runnable mTask = new Runnable() {
    public void run() {
        // just sleep for 30 seconds.
                    try {
                        Thread.sleep(3000);
                        runOnUiThread(done);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    };

    Runnable done = new Runnable() {
        public void run() {
                   // t.setText("done");
            }
        };

回答by jwalton85

@user264892

@用户264892

I found that when using a String variable I needed to either prefix with an String of "" or explicitly cast to CharSequence.

我发现在使用 String 变量时,我需要以“”字符串作为前缀或显式转换为 CharSequence。

So instead of:

所以而不是:

String Status = "Asking Server...";
txtStatus.setText(Status);

try:

尝试:

String Status = "Asking Server...";
txtStatus.setText((CharSequence) Status);

or:

或者:

String Status = "Asking Server...";    
txtStatus.setText("" + Status);

or, since your string is not dynamic, even better:

或者,由于您的字符串不是动态的,甚至更好:

txtStatus.setText("AskingServer...");

回答by user270811

per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").

根据您的建议,我正在使用 handle 和 runnables 使用“计时器”切换/更改 TextView 的内容。出于某种原因,在运行时,应用程序总是跳过第二步(“第二步:煎鸡蛋”),只显示最后(第三)步(“第三步:上鸡蛋”)。

TextView t; 
private String sText;

private Handler mHandler = new Handler();

private Runnable mWaitRunnable = new Runnable() {
    public void run() {
        t.setText(sText);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mMonster = BitmapFactory.decodeResource(getResources(),
            R.drawable.monster1);

    t=new TextView(this); 
    t=(TextView)findViewById(R.id.TextView01); 

    sText = "Step One: unpack egg";
    t.setText(sText);

    sText = "Step Two: fry egg";        
    mHandler.postDelayed(mWaitRunnable, 3000);

    sText = "Step three: serve egg";
    mHandler.postDelayed(mWaitRunnable, 4000);      
    ...
}

回答by jitain sharma

:) Your using the thread in a wrong way. Just do the following:

:) 您以错误的方式使用线程。只需执行以下操作:

private void runthread()
{

splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized(this){

                        //wait 5 sec
                        wait(_splashTime);
                    }

                } catch(InterruptedException e) {}
                finally {
                    //call the handler to set the text
                }
            }
        };

        splashTread.start(); 
}

That's it.

就是这样。

回答by Disha

setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like

将文本设置为 sam textview 两次会覆盖第一个书面文本。所以当我们第二次使用 settext 时,我们只是附加新的字符串,如

textview.append("Step Two: fry egg");

回答by Kevin Zhao

@Zordid @Iambda answer is great, but I found that if I put

@Zordid @Iambda 的回答很好,但我发现如果我把

mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);

in the run() method and

在 run() 方法和

mHandler.postDelayed(mUpdateUITimerTask, 0);

in the onCreate method make the thing keep updating.

在 onCreate 方法中使事物不断更新。