设置 onSeekBarChangeListener 导致空对象异常 [英] Setting onSeekBarChangeListener causes null object exception

查看:105
本文介绍了设置 onSeekBarChangeListener 导致空对象异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用搜索栏的值更新文本视图,但在设置 OnSeekBarChangeListener 时遇到问题.我没有任何编译错误,但是每次我尝试运行该应用程序时,都会收到空指针异常.

I'm trying to update a textview with the value of a seekbar, and I'm having trouble setting an OnSeekBarChangeListener. I don't have any compile errors, but every time I try to run the app, I get a null pointer exception.

错误说:

尝试在空对象引用上调用虚方法void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)"

Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference

尽管通过 StackOverflow 进行了搜索,但我终其一生都无法弄清楚原因.每个类似的问题,或关于如何设置 OnSeekBarChangeListener 的教程似乎都在暗示我完全按照我所做的去做.帮助!

I can't for the life of me figure out why, despite trawling through StackOverflow. Every similar problem, or tutorial on how to set an OnSeekBarChangeListener seems to suggest I do exactly what I've done. Help!

    public class MainActivity extends AppCompatActivity {
public TextView time;
public SeekBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    time = (TextView) findViewById(R.id.time);
    bar = (SeekBar) findViewById(R.id.bar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bar.setOnSeekBarChangeListener(listener);

}

private SeekBar.OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        time.setText((String.valueOf(progress/100) + ":" + String.valueOf(progress % 100)));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {


    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
};}

推荐答案

我会尝试设置这些行

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

首先在onCreate-method中,然后尝试用

first in the onCreate-method, and after that, try to find the seekBar view with

bar = (SeekBar) findViewById(R.id.bar);

请告诉我它是否解决了您的问题!

Please, let me know if it solves your problem!

findViewById() 方法将尝试查找具有指定 ID 的视图.但要做到这一点,它必须知道活动使用了哪个布局文件,以便知道在哪里搜索.这就是你用 setContentView 指出的,这就是为什么它必须排在第一位.

The findViewById() method will try to find the view with the specified ID. But to do that, it has to know which layout file is used for the activity, so that it knows where to search. That's what you point out with the setContentView, and that's why it has to come first.

这篇关于设置 onSeekBarChangeListener 导致空对象异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆