多个搜索栏 - 更有效地设置收听者?

时间:2018-04-08 00:36:34

标签: java android seekbar

我在一项活动中有12个搜索栏。每个搜索栏都需要一个听众。目前我手动为每个搜索栏设置一个监听器,这似乎并不特别有效。

任何人都可以推荐更有效的做法来设置搜索栏???

4 个答案:

答案 0 :(得分:0)

如果您的SeekBars都需要不同的交互逻辑,那么显然您需要为每个对象提供唯一的代码。但是,如果每个SeekBar执行相同的操作,您可以重用侦听器。例如:

public class SeekBarTest extends Activity{

    private Context myContext;
    public SeekBarTest(Context c){
        myContext = c;
    }

    private void initialize(){

        SeekBar seekbar1 = new SeekBar(myContext);
        SeekBar seekbar2 = new SeekBar(myContext);
        SeekBar seekbar3 = new SeekBar(myContext);

        SeekBar.OnSeekBarChangeListener myListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //logic
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //logic
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //logic
            }
        };

        seekbar1.setOnSeekBarChangeListener(myListener);
        seekbar2.setOnSeekBarChangeListener(myListener);
        seekbar3.setOnSeekBarChangeListener(myListener);
    }
}

答案 1 :(得分:0)

尝试这样的事情:

def makeUniq(in: Seq[String]): Seq[String] = {
  val m = mutable.Map.empty[String, Int]

  in.map{ e =>
    val i = m.getOrElseUpdate(e, 0) + 1
    m.update(e, i)

    s"$e$i"
  }
}

答案 2 :(得分:0)

您可以将变量发送到SeekBar初始化方法,而不必在onProgressChanged方法中创建开关。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_options);

    SeekBar volBar = initiateSeekBar(R.id.volume,R.id.volumeValue,0,1,"%");
    SeekBar playSpeedBar = initiateSeekBar(R.id.autoPlay,R.id.autoPlayValue,100, 100,"ms");
}

 private SeekBar initiateSeekBar(int barId, int textId, final int min, final int step, final String unit) {
    SeekBar bar = findViewById(barId);
    final TextView text = findViewById(textId);

    bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int value = min + progress * step;
            text.setText(value + " " + unit);
            autoPlayDelayTime = value;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    return bar;
}

答案 3 :(得分:0)

你可以做一个引用相等,像这样:

override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
    seekBar?. let {
        if (this.seekBar1 === it) {
            ...
        }
        if (this.seekBar2 === it) {
            ...
        }}
    ...
}

并在外面打电话:

seekBar1.setOnSeekBarChangeListener(this)
seekBar2.setOnSeekBarChangeListener(this)