【问题标题】:TextView remains the same it doesnt get set to any new valueTextView 保持不变,它没有设置为任何新值
【发布时间】:2011-07-16 16:57:59
【问题描述】:

我遇到了一个问题,按下按钮我尝试读取有数据进入的 DataInputstream 并显示数据。

我正在使用 while 循环来读取数据。但是Textview的动态更新并没有发生。

TextView datatextview = (TextView)findViewById(R.id.data); 

DataInputStream Din = new DataInputStream(socket.getInputStream());
Button getData= (Button)findViewById(R.id.getdata);
getData.setOnClickListener(new OnClickListener() {
    public void onClick(View v) { 
    //.......stuff .......
    try{
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int bytesRead = -1;
    String message1 = "";
    while (true) {
        message1 = "";
        data = Din.readLine();
        bytesRead = (reading).length();
        if (bytesRead != -1) {
            Log.v(TAG,"data"+data); //I'm getting the data correctly
            //But not able to update it in the TextView :(
            datatextview.setText(data);  //doesnt work
        }
    }

【问题讨论】:

    标签: android textview datainputstream


    【解决方案1】:

    您必须退出您的方法并放弃对 UI 线程的控制才能更新您的视图。您可能应该使用 AsyncTask 及其进度更新功能来执行此操作,这样您就不会占用 UI 线程。

    类似:

    public class MyTask extends AsyncTask<Void, String, Void> {
      private final TextView progress;
    
      public MyTask(TextView progress) {
        this.progress = progress;
      }
    
      @Override
      protected void onPreExecute() {
        progress.setText("Starting...");
      }
    
      @Override
      protected Void doInBackground(Void... unused) {
        ... your buffer code, including publishProgress(data); in your while loop ...
      }
    
      @Override    
      protected void onProgressUpdate(String... data) {
        progress.setText(data[0]);
        progress.invalidate(); // not sure if this is necessary or not
      }
    
      @Override
      protected void onPostExecute(Void unused) {
        progress.setText("Finished!");
      }
    }
    

    然后您可以使用以下命令创建和执行您的 AsyncTask:

    new MyTask(datatextview).execute();
    

    编辑 - 确保使用@Override,如果您的方法签名不正确,它会提醒您。

    【讨论】:

    • 谢谢你,马修。我会尽力让你知道。
    • 我的 DataStream 对象在另一个类中,并且说 myTask 是一个新类,现在我遇到了访问这些对象的问题。
    • 可以在onPostExecute中传输数据对象,也可以将AsyncTask作为内部类使用。
    • 我尝试了同样的方法,将我的读取流数据放在“doInBackground”中。但我得到的结果是“开始”。我不断地在 logcat 中获取数据。但不在 UI(textView)上。然后,一旦我停止设备,我就在 textView 中完成了。我认为问题在于我从 Class A { In OnCreate() onButtonClick call-> new GetData(readingtextview).execute(); 之类的类中调用它类 nestedB 扩展 Async{ doInBackground() publishProgress() } ` }
    • 我想说我正在使用嵌套类方法,但它不起作用。我刚刚在我的 TextView 中“开始”
    【解决方案2】:

    马修就在这里,但要详细说明...

    如果您是从一个线程执行此操作,那么您可能会因为循环太快而陷入困境,UI 永远没有机会使用您的新值重绘。如果您想从线程调用 View.invalidate() 强制重绘 UI。

    如果您再次从主线程(您绝对应该重新考虑)执行此操作,您将陷入循环并且 UI 无法重绘...您希望所有 View.postInvalidate() 强制重绘 UI。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多