gpt4 book ai didi

java - 后台线程中的 Progress bar.setProgress(variable)

转载 作者:行者123 更新时间:2023-12-01 17:47:01 25 4
gpt4 key购买 nike

这是我在堆栈上的第一个问题(很棒的社区,谢谢!)

所以,我有这个问题:

我正在开发一个带有选项卡布局的 Android 应用程序。每当我导航到“状态”选项卡时,我都想显示一个根据变量值更新的圆形进度条。我们将这个变量称为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();


}

}

在此 fragment 中,我创建了 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 basics: running code in the UI thread

总而言之,Android 需要某些类型和部分的代码才能在特定上下文中运行。许多工具(例如处理程序)可以帮助完成这些任务,但一开始就很难学习。

关于java - 后台线程中的 Progress bar.setProgress(variable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60852551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com