Step 07 - Radio Button

In donateButtonPressed we need to discover which payment method has been selected. Our RadioGroup documentation is here:

  • <http://developer.android.com/reference/android/widget/RadioGroup.html>

This looks like the method we need:

This is a revised version of donateButtonPressed()

1. public void donateButtonPressed (View view)
2. {
3. int amount = amountPicker.getValue();
4. int radioId = paymentMethod.getCheckedRadioButtonId();
5. String method = "";
6. if (radioId == R.id.PayPal)
7. {
8. method = "PayPal";
9. }
10. else
11. {
12. method = "Direct";
13. }
14. Log.v("Donate", "Donate Pressed! with amount " + amount + ", method: " + method);
15. }

Run it now and verify we are getting the correct logs.

We can simplify it somewhat by reducing the if statement to a singlle line:

1. String method = radioId == R.id.PayPal ? "PayPal" : "Direct";

This is the Java ternary operator:

  • <http://marxsoftware.blogspot.ie/2010/09/how-i-learned-to-stop-worrying-and-love.html>

This is the complete activity class:

1. package com.example.donation;

3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.res.Resources;
6. import android.util.Log;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.RadioGroup;
11. import android.widget.NumberPicker;
12. import android.widget.ProgressBar;

15. public class Donate extends Activity
16. {
17. private Button       donateButton;
18. private RadioGroup   paymentMethod;
19. private ProgressBar  progressBar;
20. private NumberPicker amountPicker;

22. @Override
23. protected void onCreate(Bundle savedInstanceState)
24. {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_donate);

28. donateButton  = (Button)       findViewById(R.id.donateButton);
29. paymentMethod = (RadioGroup)   findViewById(R.id.paymentMethod);
30. progressBar   = (ProgressBar)  findViewById(R.id.progressBar);
31. amountPicker  = (NumberPicker) findViewById(R.id.amountPicker);

33. amountPicker.setMinValue(0);
34. amountPicker.setMaxValue(1000);
35. }

37. @Override
38. public boolean onCreateOptionsMenu(Menu menu)
39. {
40. getMenuInflater().inflate(R.menu.donate, menu);
41. return true;
42. }

44. public void donateButtonPressed (View view)
45. {
46. int amount = amountPicker.getValue();
47. int radioId = paymentMethod.getCheckedRadioButtonId();
48. String method = radioId == R.id.PayPal ? "PayPal" : "Direct";
49. Log.v("Donate", "Donate Pressed! with amount " + amount + ", method: " + method);
50. }
51. }