0

我有一个带有 3 个片段的选项卡式活动。第一个片段允许用户选择一个测试,第三个片段有一个计时器、一个文本视图和一些按钮。到目前为止,第二个片段中没有任何内容。

在片段 3 中,我有一个启动计时器的按钮,一旦启动计时器,textview 会每分钟刷新一次,显示经过的时间。到目前为止一切正常。

问题:一旦计时器启动,如果我选择片段 1 并返回片段 3,计时器将停止更新 textView。我知道 timer_elapsed 运行正常,只有 textview 没有更新。

我试过 FragmentActivity.RunOnUiThread(() => {}); 这工作正常,直到片段被切换。

我确实尝试使用 Loopers.MainLooper 来更新屏幕,但问题仍然存在。

// update the screen every minute
                if (mActivity != null)
                { 
                    mActivity.RunOnUiThread(() =>
                    {

                        // set the progress bar
                        progressBar.Progress = i32ProgressBarValue;
                        textViewPercentage.Text = i32ProgressBarValue + "%";

                        // set the text view
                        textViewTestTime.Text = $"{Globals.i32Days}" + "D :" + $"{Globals.i32Hours}" + "H :" + $"{Globals.i32Mins}" + "M";
                    });
                }

我希望 textView 在片段切换并返回到片段 3 时继续正确更新

4

1 回答 1

1

我在TabbedActivity(使用BottomNavigationView)中编写了一个示例使用定时器,它也有三个片段,在第三个片段中,我使用按钮启动定时器以每两秒更新一次按钮的文本,它运行良好(在切换片段时也适用),以下是第三个片段中的代码,您可以参考它:

Timer _dispatcherTimer;
TimerCallback timerDelegate;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
        View view = inflater.Inflate(Resource.Layout.fragment_account, container, false);
        init(view);
        timerDelegate = new TimerCallback(Tick);

        return view;
    }
   private void init(View view)
    {
        button = view.FindViewById<Button>(Resource.Id.mybutton);
        button.Click += delegate
        {
            _dispatcherTimer = new System.Threading.Timer(timerDelegate, null, 0, 2000);
        };
    }
    private void Tick(object state)
    {

        this.Activity.RunOnUiThread(() =>
        {
            //do something
              Random reRandom = new Random();
              int s = reRandom.Next(1000);
                button.Text = s.ToString();
        });
    }
于 2019-03-28T02:20:58.560 回答