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

24
我正在使用自定义标题视图, 希望在线程工作时在标题视图中显示/隐藏一个进度条。
这是我的标题视图的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>

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

titleProgress = (ProgressBar)findViewById(R.id.progress_small_title);
titleProgress.setVisibility(View.INVISIBLE);

这是我在线程中所做的:

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

但是进度条没有任何变化,它从未显示。请有人告诉我代码出了什么问题?

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

谢谢。

5个回答

16

尝试以下几件事情:

1) (这可能不是问题所在)请确保"titleProgress"是易失性的。

2) 尝试添加一些postInvalidate()titleProgress.postInvalidate()来触发重绘。

3) 你是否向像巨大绿色机器人的祭坛上献祭了一台x486机器?(开个玩笑)

让我知道以上两点(如果你真的感到绝望,可以尝试第三点)是否有帮助。


3
已经尝试了前两种方法,但并没有帮助!我很绝望,所以我想这就需要第三种方法了? ;) - lostInTransit
第三个选项是解决所有问题的最佳方案... 哈哈 - Rodrigo

5

4

使用Handlers进行通信,

  1. execute your thread
  2. into run() : you should send a message to the Handler which will update the progressBar (Horizontal of course ) : handler.sendMessage(handler.obtainMessage());
  3. in your Activity , you should override the method handleMessage(Message msg ) : like this

    handler = new Handler(){
      @override
      public void handleMessage(Message msg ) 
      {
        //here you write the code which will update your progressBar 
      }
    };
    

只有当您的线程包装在活动类中时,才能正常工作。 - Miky

1
你的布局正确吗?你尝试使用垂直布局先让它工作了吗?只是为了看看当你启动活动时进度条是否可见?

0
尝试将 ProgressBar 的样式更改为水平:
style="?android:attr/progressBarStyleHorizontal"

原始的

style="?android:attr/progressBarStyleSmall"

提供一个圆形的“进度条”,但在标题栏中无法完全显示。


我甚至尝试了progressBarStyleSmallTitle,这应该适合默认标题栏。但即使这样也没有显示出来。 - lostInTransit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接