This is my 1st activity
public void onClick(View v) {
switch (v.getId()) {
case R.id.setButton:
int cpv= carbPValue;
int ppv = proteinPValue;
int fpv=fatPValue;
Intent intent = new Intent ( this, AdjustMacronutrients.class );
intent.putExtra ( "carbP", cpv );
intent.putExtra ( "proteinP", ppv );
intent.putExtra ( "fatP", fpv );
startActivity(intent);
finish();
}
}
This is my 2nd activity :
I have 3 integer value pass from 1st activity which is cpv
, ppv
, fpv
.
How can i set those value inside the number picker as default, before user pick the number. And show the number in the TextView
after user select from each 3 different number picker ,last and pass back the integer value to the 1st activity.
Bundle extras = getIntent().getExtras();
cpv=extras.getInt("carbP");
ppv=extras.getInt("proteinP");
fpv= extras.getInt("fatP");
NumberPicker.OnValueChangeListener onValueChanged = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker[] nps = new NumberPicker[3];
nps[0] = (NumberPicker) findViewById(R.id.carbPercentage);
nps[1] = (NumberPicker) findViewById(R.id.proteinPercentage);
nps[2] = (NumberPicker) findViewById(R.id.fatPercentage);
int sum = 0;
for (int i = 0; i < 3; i++) {
String[] values = nps[i].getDisplayedValues();
sum += Integer.parseInt(values[nps[i].getValue()]);
}
TextView tv = (TextView) findViewById(R.id.totalPercentage);
tv.setText(String.valueOf(sum)+" %");
}
};
NumberPicker[] nps = new NumberPicker[3];
nps[0] = (NumberPicker) findViewById(R.id.carbPercentage);
nps[1] = (NumberPicker) findViewById(R.id.proteinPercentage);
nps[2] = (NumberPicker) findViewById(R.id.fatPercentage);
String[] values = new String[21];
for (int i = 0; i < values.length; i++) {
values[i] = Integer.toString(i * 5);
}
for (int i = 0; i < 3; i++) {
nps[i].setMaxValue(values.length - 1);
nps[i].setMinValue(0);
nps[i].setDisplayedValues(values);
nps[i].setOnValueChangedListener(onValueChanged);
}
Rami
You can use:
- NumberPicker.setValue() method to set your default values.
eg:
nps[0].setValue(cpv);
nps[1].setValue(ppv);
nps[2].setValue(fpv);
- NumberPicker.getValue() to get the values and update your text.
eg:
tv.setText(String.valueOf(nps[0].getValue())); // or just tv.setText(""+nps[0].getValue());
- Activity.onActivityResult() callback to pass new values to your 1st activity (You can find an example in this answer).
来源:https://stackoverflow.com/questions/34085608/passing-number-from-1st-activity-to-the-number-picker