0

这是我的第一个活动

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

这是我的第二个活动:

我从第一个活动中传递了 3 个整数值,即cpv, ppv, fpv

在用户选择数字之前,如何将数字选择器中的这些值设置为默认值。并TextView在用户从每个 3 个不同的数字选择器中选择后显示数字,最后将整数值传递回第一个活动。

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

1 回答 1

0

您可以使用:

例如:

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

例如:

tv.setText(String.valueOf(nps[0].getValue())); // or just tv.setText(""+nps[0].getValue());
于 2015-12-04T12:02:20.157 回答