更新Seekbar值

时间:2018-03-26 15:44:53

标签: android seekbar

我有一个搜索栏,其中有以下间隔: 最小值= 100000,最大值为2500000,间隔为25000

我需要在编辑文本更改时更新我的​​搜索栏,并验证不在25000范围内的数字

这是我的代码:

int mininumloan_amount = 100000;
int maximum_loan_amount = 2500000;

int interval = 25000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seekbar);


    loanAmountSeekbar = findViewById(R.id.loanAmountSeekbar);
    loanAmountValue = findViewById(R.id.loanAmountValue);

    setEditText();
    setSeekBar();
}

private void setEditText() {

    loanAmountValue.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            int porgress = Math.round((int) Double.parseDouble(charSequence.toString()));
            if (porgress > mininumloan_amount)
                loanAmountSeekbar.setProgress(porgress);
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
}

private void setSeekBar() {

    loanAmountSeekbar.setMax((maximum_loan_amount - mininumloan_amount) / interval);
    loanAmountSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            double value = mininumloan_amount + (i * interval);

            loanAmountValue.setText(value + "");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}

请帮忙

2 个答案:

答案 0 :(得分:1)

我觉得最容易使用基于百分比100的进度条。

所以简单地说,我会将输入转换为您希望允许贷款的最大数量的百分比。

以下是我用于演示的代码,以获得概念验证:

  private void setEditText() {

    loanAmountValue.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      }

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
          double actualProgress = computeProgress(charSequence);
          Log.d(TAG, "Progress: " + actualProgress);

          // if the progress is 100 or less its in range
          if(actualProgress <= 100) {
            loanAmountSeekbar.setProgress((int) actualProgress);
          }
      }

      @Override
      public void afterTextChanged(Editable editable) {

      }
    });
  }

  /* 
      Mostly where all the magic is, we convert input to percent
      then check against minimum value, tell user to enter more.
      If the percent is more than 100, we default to 100%.
  */
  private Double computeProgress(CharSequence charSequence) {
    try {
      // Parse the value, also, used android:inputType="decimalNumber" in xml
      double editTextNumber = Double.parseDouble(charSequence.toString());

      if(editTextNumber < interval){
        Toast.makeText(MainActivity.this, "Please enter a value greater than "+ interval, Toast.LENGTH_SHORT).show();
        return 0.0;
      }

      // Turn the number into a percentage of the max value
      double percentageOfMax = editTextNumber / maximum_loan_amount;

      // Turn the percentage back into a number between 0 and 100
      double percent = 100 * percentageOfMax;

      // handle the max percent
      if(percent > 100){
        return 100.0;
      }else {
        return percent;
      }

    } catch (NumberFormatException ex) { // just in case something odd
      ex.printStackTrace();
      Toast.makeText(MainActivity.this, "Unable to parse: " + charSequence.toString(), Toast.LENGTH_SHORT).show();
    }catch(ArithmeticException ex){ // extra since we check a min above, probably can exlude this 
      Toast.makeText(MainActivity.this, "value must not be 0 ", Toast.LENGTH_SHORT).show();
    }

    return 0.0;
  }

  private void setSeekBar() {

    loanAmountSeekbar.setMax(100);
    loanAmountSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        if(b){
          double value = interval * i;
          loanAmountValue.setText(value + "");
        }
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {

      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {

      }
    });
  }

<强>声明 这是一个非常快速的解决方案,因此您可能需要探索其他错误处理。但基本思路是,接受输入,将其转换为100的百分比。

祝你好运,快乐的编码!

答案 1 :(得分:0)

尝试以下方法:

public class Demo1 extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener{

private SeekBar sb;
private EditText edt;
private SharedPreferences sp;

private String value;

int mininumloan_amount = 100000;
int maximum_loan_amount = 2500000;

int interval = 25000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seekbar);

    sp = getSharedPreferences("SAVED_VALUES",
            0);

    sb = findViewById(R.id.sb);
    sb.setOnSeekBarChangeListener(this);

    edt = findViewById(R.id.edt);

    if(sp != null){

        if(getsavedValue() != -1) {
            sb.setProgress(getsavedValue());
            edt.setText(String.valueOf(getsavedValue() * interval + mininumloan_amount));
        }

    }else{
        sb.setProgress(0);
        edt.setText(mininumloan_amount);
    }

    edt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            value = s.toString();
        }
    });

    edt.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER){

                //TODO: handle case when user presses back while the input is empty).

                if(!value.isEmpty()) {
                    if (Integer.valueOf(value) > mininumloan_amount ||
                            Integer.valueOf(value) < maximum_loan_amount) {
                        sb.setProgress((Integer.valueOf(value) - mininumloan_amount) / interval);// values are rounded
                        saveValue((Integer.valueOf(value) - mininumloan_amount) / interval);
                    } else {
                        if (Integer.valueOf(value) < mininumloan_amount) {
                            edt.setText(mininumloan_amount);
                            sb.setProgress(0);
                            saveValue(0);
                        } else if (Integer.valueOf(value) > maximum_loan_amount) {
                            edt.setText(maximum_loan_amount);
                            sb.setProgress(100);
                            saveValue(100);
                        }
                    }
                }
                return true;
            }
            return false;
        }
    });


}

@Override
protected void onPause() {
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    if(sp != null){

        sb.setProgress(getsavedValue());
        edt.setText(String.valueOf(getsavedValue()*interval+mininumloan_amount));

    }
}


@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    edt.setText(String.valueOf((progress*interval) + mininumloan_amount));
    saveValue(progress);

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}

private void saveValue(int value){

    if(sp != null) {

        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(getResources().getString(R.string.value), value);
        editor.apply();
    }

}

private int getsavedValue(){

    if(sp != null) {
        return sp.getInt(getResources().getString(R.string.value), 0);
    }
    return -1;

}

}

activity_seekbar.xml -----------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100">

<SeekBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sb"
    android:max="100"
    android:layout_marginTop="28dp"
    android:layout_weight="80"
    android:progress="0"/>

<EditText
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:hint="loan amount"
    android:id="@+id/edt"
    android:inputType="number"
    android:layout_weight="20">
</EditText>

</LinearLayout>