简体   繁体   中英

Multiple SeekBars listener

I have multiple seekbar on the same view :

barheures = (SeekBar)findViewById(R.id.barheures); // make seekbar object
        barheures.setOnSeekBarChangeListener(this); // set seekbar listener.
        // since we are using this class as the listener the class is "this"
        barminutes = (SeekBar)findViewById(R.id.barminutes);
        barminutes.setOnSeekBarChangeListener(this); 

And here is the listener:

@Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
    // TODO Auto-generated method stub
    Log.v("", "" + bar);
    textMinutes.setText("" + progress + "Minute(s)" );
    textHours.setText("" + progress + "Heure(s)" );
}

I wanna make something different if the first OR the second bar have moved into the same listener (is it the good practice?), but how to?? Here I have the app that don't do what I want

Now then you have 2 seekbars with the following ids:

  1. barheures - its id: R.id.barheures
  2. barminutes - its id: R.id.barminutes

Now in the onProgressChanged(SeekBar bar, int progress, boolean fromUser) method, Do the following:

@Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
    // TODO Auto-generated method stub
    Log.v("", "" + bar);

    switch (bar.getId()) {

    case R.id.barheures:
        textHours.setText("" + progress + "Heure(s)");
        break;

    case R.id.barminutes:
        textMinutes.setText("" + progress + "Minute(s)");
        break;
    }
}


    

Instead of comparing resource ids, you can also just check the SeekBar object for equality. Example:

private SeekBar bar1;
private SeekBar bar2;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    ...

    bar1 = (SeekBar) findViewById(R.id.bar1);
    bar2 = (SeekBar) findViewById(R.id.bar2);

    ...
}

@Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromUser)
{
    if (bar.equals(bar1))
    {
        // do something
    }
    else if (bar.equals(bar2))
    {
        // do something else
    }
}

I prefer doing it this way because then you only ever reference the id of each SeekBar resource once (in your onCreate ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM