Passing number from 1st activity to the number pic

2020-05-01 10:10发布

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);
        }

1条回答
够拽才男人
2楼-- · 2020-05-01 11:02

You can use:

eg:

nps[0].setValue(cpv);
nps[1].setValue(ppv);
nps[2].setValue(fpv);

eg:

tv.setText(String.valueOf(nps[0].getValue())); // or just tv.setText(""+nps[0].getValue());
查看更多
登录 后发表回答