简体   繁体   中英

Android: Pass an integer from NumberPicker to another activity

I am using the built in NumberPicker to have the user choose a number. Then the user will hit the "OK" button to confirm and the resulting action will open up another activity. I want the number that the user chooses to be passed through to the other activity when the user hits the "OK" button. I have done buttons that result in opening up a new activity and I know that the NumberPicker has a getValue() and you can pass stuff through with putExtra(), but I am not sure how to combine those with the onClick method. How do I go about doing this?

public class Source1 extends Activity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_1);
...(NumberPicker code)
}

@Override
public void onClick(View v) {
    int x = ((NumberPicker) v).getValue();
    Intent intent = new Intent(this, Destination.class);
    intent.putExtra("VarName", x);
    startActivity(intent);
}
}

This is the xml for my button:

<Button
    android:id="@+id/Id_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/numberPicker1"
    android:layout_centerHorizontal="true"
    android:onClick="methodName"
    android:text="@string/Ok" />

That was my attempt. Is this right/what needs to change? Do I even need the onClick in the button code since I am using the onClick method in the class?

Change your code as to get selected value from NumberPicker on Button click:

@Override
public void onClick(View v) {

    NumberPicker numPicker = (NumberPicker)findViewById(R.id.NumberPicker_id);
    int x = numPicker.getValue();
    Intent intent = new Intent(this, Destination.class);
    intent.putExtra("VarName", x);
    startActivity(intent);
}

Is this right/what needs to change?

The best way to test whether its right is: try to read VarName in Destination . But see imran khan's answer.

Do I even the onClick in the button code since I am using the onClick method in the class?

No, you should choose one or the other. Either use:

  1. onClick="methodName" in the XML, with public void methodName(View v) {} in Source1

  2. implement OnClickListener and use numberPicker.setOnClickListener(this); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM