java - 线程问题,无法更改外部 TextView 的值

标签 java android multithreading

我有一个 android 线程类,它必须更改外部 TextView 的值,但它不会更改它:S。我对其进行调试,可以看到线程执行了更改 TextView 值的行,但它没有反射(reflect)在该值上。

public class AugmentedRealitySampleActivity extends Activity {

    private TextView tv2;
public void onCreate(Bundle savedInstanceState) 
{   
       super.onCreate(savedInstanceState);
       tv2=new TextView(getApplicationContext());
       tv2.setText("Test2");
       myThread t = new myThread();
       t.start();
}

 public class myThread extends Thread 
 {
    public void run() 
    {
        Looper.prepare();
        tv2.append("\n AAA");
        Looper.loop();
    }
 }
}

编辑;以完整模式发布的代码:

private class myAsyncTask extends AsyncTask<Void, Void, Void> 
    {
        boolean condition = true;                

        protected Void doInBackground(Void... params) 
        {
            while( condition )
            try 
            {
                publishProgress();
                Thread.sleep( 1000 );
            }catch (InterruptedException e) {e.printStackTrace();}
            return null;
        }

        protected void onProgressUpdate(Void... values)
        {
            //Update your TextView
            if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) //si el GPS está desactivado
            {
                boolean visible=false;
                float a = 80; //a=bearingTo
                float b =azimuth; 
                float d = Math.abs((a - b)) % 360;
                float r = d > 180 ? 360 - d : d;

                if (Math.abs(r)<21 && Math.abs(inclination)<30)
                    visible=true;

                if (visible)
                {
                    tv2.append("\nIs Visible?: true "+ r);
                    poi.setVisibility(View.VISIBLE);

                    ////////CALCULAMOS COORDENADA X DEL POI///////
                    float leftSideFovDegree=azimuth-21;
                    if (leftSideFovDegree<0)
                        leftSideFovDegree+=360;
                    float dist=anglesDistance(leftSideFovDegree,a);
                    float xCoordPercent=(dist*100)/42; //xCoordPercent es el porcentaje de X respecto al horizontal de la pantalla, en el que estará el objeto                  
                    if (a<0)//si el bearingTo es negativo, entonces la cordenada X se invierte
                        xCoordPercent=100-xCoordPercent;

                    tv2.append("\nxCoordPercent: "+ xCoordPercent);

                    ////////CALCULAMOS COORDENADA Y DEL POI///////
                    //float yCoordPercent= (float)(42.7377 * Math.pow(Math.E,(0.0450962*inclination)));         
                    float yCoordPercent= (float)(33.0459 * Math.pow(Math.E,(0.056327*inclination)));
                    tv2.append("\nyCoordPercent: "+ yCoordPercent);

                    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
                    int w = display.getWidth();
                    int h = display.getHeight();

                    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                    position.leftMargin = (int)(w*(xCoordPercent/100));
                    position.topMargin  = (int)(h*(yCoordPercent/100));
                    poi.setLayoutParams(position);
                }
                else
                {   
                    tv2.append("\nIs Visible?: false "+ r);
                    poi.setVisibility(View.GONE);
                }
            }
        }
    }

最佳答案

这可能是因为您的线程不是 UI 线程。所有 View 的更新都必须在 UI 线程上完成。

尝试这样做:

runOnUiThread( new Runnable() {
  @Override
  public void run() {
    tv2.append("\n AAA");
  }
});

或者更好 - 将您的线程转换为 AsyncTask像这样:

private class myAsyncTask extends AsyncTask<Void, Void, Void> {
            boolean condition = true;                

    @Override
    protected Void doInBackground(Void... params) {
        while( condition )
         try {
            // Do your calculations
            publishProgress();
            Thread.sleep( 200 );
         } catch (InterruptedException e) {
            e.printStackTrace();
         }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        //Update your TextView
    }
}

您不需要创建新线程:

new myAsyncTask().execute();

关于java - 线程问题,无法更改外部 TextView 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597139/

相关文章:

python - 如何在 tkinter 中运行多个线程

Java MIDI 音序器替代品

android - 在 ARM 上网本 (Ubuntu) 上运行 Android SDK

Java:setText() 和线程

android - Firebase 部署不断给我一个错误 : Parse Error in remoteconfig. template.json

java - 如何在 CRONET 中将 json 对象作为 post 请求发送?

java - 在等待另一个线程时让当前线程进入休眠状态

java - UseConcMarkSweepGC 已弃用,它的替代品是什么?

java - 在 Commons Daemon 中正确使用 Procrun 中的 DependsOn 选项

java - 在主 Activity 上无法在 Android 中显示弹出窗口 Android 无法在未调用 Looper.prepare() 的线程内创建处理程序