更新Android UI无效

时间:2014-06-26 18:52:05

标签: java android multithreading user-interface

我正在搜索2小时的小错误,导致此代码无效:

活动:

UpdateThread t;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_fullscreen);
}
@Override
protected void onResume() {
    t = new UpdateThread(this, this);
    t.start();
    super.onResume();
}

线程:

public UpdateThread(FullscreenActivity a, Context c) {
    this.c = c;
    this.a = a;
}
@Override
public void run() {
    if(enabled) return;
    enabled = true;
    while(true) {
        a.runOnUiThread(new Runnable() {

            @Override
            public void run() {

                RelativeLayout view = (RelativeLayout) a.findViewById(R.id.view);
                view.removeAllViews();
                    try {
                        TextView t = new TextView(c);
                        t.setText("asd");
                        t.setVisibility(View.VISIBLE);
                        t.setX(22);
                        t.setY(123);
                        t.setScaleX(0.9f);
                        t.setScaleY(0.9f);
                        t.setBackgroundColor(Color.YELLOW);
                        view.addView(t);
                    } catch(Exception e) {e.printStackTrace();}

                Log.d("Finished drawing!"," drawed!");
            }
        });
    }

布局XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" 
    android:id="@+id/asd"/>

</RelativeLayout>

此代码应将TextView添加到FullscreenActivity,但没有任何反应。

我使用Android级别12,所有软件都是最新的,我的手机是SGS3。 谢谢你的帮助,我期待着解决方案:)

0 个答案:

没有答案