[英]Android - ProgressBar setProgress() method doesn't update the progress bar drawable
[英]Progress bar.setProgress(variable) in a background thread
这是我关于堆栈的第一个问题(很棒的社区,谢谢!)
所以,我有这个问题:
我正在开发一个带有选项卡布局的 android 应用程序。 每当我导航到“状态”选项卡时,我都想显示一个根据变量值更新的圆形ProgressBar 。 让我们称这个变量为prog 。 此外,我想在 ProgressBar 的中心显示一个TextView ,它显示与prog相同的值。
我想出了这部分代码:
public class StatusFragment extends Fragment
{
private ProgressBar torqueRefProgressBar;
private TextView torqueRefTextView;
RunningThreadExample r;
private Thread t1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the layout for this fragment
return ...;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
// Initializations and other parts not relevant for the question...
this.torqueRefProgressBar = getView().findViewById(R.id.torqueRefProgressBar);
this.torqueRefTextView = getView().findViewById(R.id.torqueRefTextView);
t1 = new Thread( this.torqueRefProgressBar, this.torqueRefTextView)); // passing arguments by value but values are references to the objects, therefore I'm passing by ref
t1.start();
}
}
在这个片段中,我创建了 ProgressBar 和 TextView,然后将它们传递给 Runnable,如下所示
public class RunningThreadExample implements Runnable
{
ProgressBar torqueRefProgBar_thread;
TextView torqueRefTextView_thread;
public RunningThreadExample(ProgressBar progressBar, TextView textView)
{
this.torqueRefProgBar_thread = progressBar;
this.torqueRefTextView_thread = textView;
this.endScale = this.torqueRefProgBar_thread.getMax();
}
@Override
public void run()
{
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
float i = 0;
double temp = 0;
while(Running)
{
try
{
Thread.sleep(1000/60); // update freq 60Hz
}
catch (InterruptedException e)
{
e.printStackTrace();
}
temp = getCurrentVariableValue(); // Not shown here (returns a double)
this.torqueRefProgBar_thread.setProgress((int) temp);
this.torqueRefTextView_thread.setText(String.valueOf(temp));
}
Log.i(INFO_TAG,"Finishing thread!!!!!");
}
}
我希望此更新在应用程序运行时一直运行(因此我忽略了AsyncTask )。 一段时间后,ProgressBar 会停止更新,而 TextView 继续正常工作,没有任何问题。
我一直在读到一个可能的原因可能是调用setProgress(temp)可能会卡住 UI。 但是,当 TextView 仍在工作时,我无法理解。
你能建议一个更好的方法来更新进度条吗?
谢谢!
看到这个线程:
总而言之,Android 需要某些类型和部分的代码才能在特定上下文中运行。 许多工具(例如处理程序)可用于帮助完成这些任务,但开始时很难学习。
您不能从主线程以外的任何线程影响视图。 在run()
方法中run()
以下操作
runOnUiThread(new Runnable() {
//
run(){
this.torqueRefProgBar_thread.setProgress((int) temp);
} this.torqueRefTextView_thread.setText(String.valueOf(temp));
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.