1

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

所以,我有这个问题:

我正在开发一个带有选项卡布局的 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();


    }

}

在这个片段中,我创建 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 仍在工作时,我无法理解。

你能建议一个更好的方法来更新进度条吗?

谢谢!

4

2 回答 2

0

看到这个线程:

Android 基础:在 UI 线程中运行代码

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

于 2020-03-25T16:03:31.727 回答
0

您不能从除主线程之外的任何线程影响视图。run()在方法中执行以下操作

runOnUiThread(new Runnable() { 
// 
run(){

 this.torqueRefProgBar_thread.setProgress((int) temp);
      }      this.torqueRefTextView_thread.setText(String.valueOf(temp));
);
于 2020-03-25T16:05:19.000 回答