Search code examples
androidandroid-seekbar

SeekBar inside another class


I have created a SeekBar that displays distance. This distance is used in order to show a circle with a specific distance as its radius.

In my onCreate I have the following lines:

SeekBar seekBar = findViewById(R.id.sb_radius);
seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

Then, the class where I use it is as follows:

   private void Search_Map(float dpWidth, float dpHeight, Object Lat, Object Lon) {

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvDistance.setText( "Progress: " + progress );
            Show_Map(dpWidth, dpHeight, Lat, Lon, progress*1000);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
} 

My problem is that it never does any action because I'm getting an error at my onCreate saying:

cannot resolve symbol seekBarChangeListener.

How can I use the seekbar inside my class and yet to make the listener work?

Thank you


Solution

  • Remove seekBar.setOnSeekBarChangeListener(seekBarChangeListener); line from onCreate and add it to end of Search_Map

    class ClassName{
    Seekerbar seekerbar;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout_name);
            seekBar = findViewById(R.id.sb_radius);
    
    }
    private void Search_Map(float dpWidth, float dpHeight, Object Lat, Object Lon) {
    
        SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
    
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // updated continuously as the user slides the thumb
                tvDistance.setText( "Progress: " + progress );
                Show_Map(dpWidth, dpHeight, Lat, Lon, progress*1000);
            }
    
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // called when the user first touches the SeekBar
            }
    
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // called after the user finishes moving the SeekBar
            }
        };
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    
    } 
    }