Android - 使用runOnUiThread从线程进行UI更改

los*_*sit 24 android

我正在使用自定义标题视图,并希望在线程工作时在标题视图中显示/隐藏进度条.

这是我的标题视图的XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <Button
        android:id="@+id/image_left_btn"
        android:layout_width="75dip" 
        android:layout_height="wrap_content" 
        android:text="Back"
    />
    <TextView
        android:id="@+id/image_title_text"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_weight="1"
        android:textSize="20dip"
        android:textStyle="bold"
        android:textColor="#fff"
        android:layout_gravity="center"
        android:gravity="center"
        android:paddingLeft="8dip"
        android:paddingRight="8dip"
    />
    <ProgressBar 
        android:id="@+android:id/progress_small_title"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="75dip"
        android:layout_height="wrap_content" 
        android:paddingRight="8dip"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在我的Activity中,将此设置为自定义标题栏后,我执行此操作

titleProgress = (ProgressBar)findViewById(R.id.progress_small_title);
titleProgress.setVisibility(View.INVISIBLE);
Run Code Online (Sandbox Code Playgroud)

其中titleProgress是ProgressBar对象.

这就是我在我的线程中所做的

runOnUiThread(new Runnable() {
    public void run() {
        titleProgress.setVisibility(View.VISIBLE);
    }
});
//long operation here
runOnUiThread(new Runnable() {
    public void run() {
        titleProgress.setVisibility(View.INVISIBLE);
    }
});
Run Code Online (Sandbox Code Playgroud)

但进度条没有变化.永远不会显示.有人可以告诉我代码有什么问题吗?

是否可以在自定义标题中显示标题进度条?

谢谢.

has*_*man 16

几件事要尝试:

1)(这可能不是这样)确保" titleProgress"是不稳定的.

2)尝试投掷一些postInvalidate()titleProgress.postInvalidate()在那里触发重绘.

3)你是否在类似巨型绿色机器人的变体上对x486机器进行了诅咒?(开玩笑)

让我知道如果前两个(如果你真的绝望,第三个)让你到任何地方.

  • 已经尝试了前两个但没有帮助!绝望的我是这样的,我猜这要求3?;) (3认同)

Edd*_*ied 5

在这种情况下你应该使用的是AsyncTask,请参阅 http://developer.android.com/reference/android/os/AsyncTask.html

如果您没有定位到1.5之前版本的Android,则必须使用另一个名为UserTask的类.请参阅http://android-developers.blogspot.com/2009/05/painless-threading.html