在侦听器中更改TextView的文本时出现问题

时间:2018-12-30 17:40:18

标签: android textview

我试图使TextView看起来像计时器,并控制SeekBar所显示的时间。

首先,我收到消息TextView必须是Final,但是当我更改时,无法在侦听器中使用setText更改TextView

如何解决此代码?

    SeekBar seekBar = findViewById(R.id.seekBar);
    final TextView timeView = findViewById(R.id.timeView);

    seekBar.setMax(600);
    seekBar.setProgress(30);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int minutes = progress / 60;
            int seconds = progress - (progress * 60);

            timeView.setText(Integer.toString(minutes), ":", Integer.toString(seconds));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}

4 个答案:

答案 0 :(得分:0)

尝试创建一个public Textview。 因此,替换此行

final TextView timeView = findViewById(R.id.timeView); 

使用

timeView = findViewById(R.id.timeView); 

并添加

TextView timeView;

通过您的OnCreate方法。

答案 1 :(得分:0)

您的代码唯一的问题是setText()方法的语法。
setText()以一个String(CharSequence)作为参数,因此请更改此值:

timeView.setText(Integer.toString(minutes), ":", Integer.toString(seconds));

对此:

timeView.setText(Integer.toString(minutes) + ":" + Integer.toString(seconds));

答案 2 :(得分:0)

替换

timeView.setText(Integer.toString(minutes), ":", Integer.toString(seconds));

timeView.setText(Integer.toString(minutes)+ ":"+ Integer.toString(seconds));

答案 3 :(得分:-1)

实际上,简单的解决方案是简单地更改OP希望在setText()方法内使用onProgressChanged()的代码行:处理这些代码的setText()方法没有覆盖参数。简单的解决方案(如许多答案所述):

timeView.setText(Integer.toString(minutes) + ":" + Integer.toString(seconds));



但是...更深入
TL; DR

最初,OP只是想在TextView timeView方法中使用onCreate(),但是编译器警告说,他们需要在final的前面添加TextView timeView为了能够在匿名内部类timeView中使用SeekBar.OnSeekBarChangeListener()

但是,一般而言,关键字final表示变量在初始化后不能更改。尽管在这种特殊情况下,使用final可能会造成混乱,但允许使用TextView来更改setText()

主要问题是范围。 SeekBar.OnSeekBarChangeListener()是匿名内部类,onCreate()是封闭的块。这(基本上)意味着内部类实际上并不属于onCreate(),并且timeView在方法onProgressChanged() scope 之外。

当然,在方法变量final中添加TextView timeView可以“解决”问题-在这种特殊情况(和某些类似情况)下,但并非在所有情况下 ;因此,我相信使用final是违反直觉的。

将变量int count = 0String showTime = "Show time";放在onCreate()内部,但在匿名内部类之外。如果要在匿名内部类中使用变量,则编译器将再次发出警告,必须声明变量final。但是这样做,将无法再更改它们。实际上,如果试图更改这些值,该代码甚至都不会编译。通过使TextView timeView;为类变量(即,将其移至onCreate()方法之外),该字段的范围将扩大为包括匿名内部类。变量int count = 0String showTime = "Show time";的情况也是如此-使它们成为类变量也将扩大其范围以包括匿名内部类,以便可以在方法{{1}中使用和更改它们}。因此,我认为使用类变量代替onProgressChanged()更直观。

检查Java文档:
Anonymous Classes
Accessing Members of an Enclosing Class