0

quick question. How would I go about to pass a checked radio button value to other activities using intent? Do I need to also use sharing preference to save the value?

I wanted to do something like "when user selected the radio button (for example: red,blue,green, yellow) and all the textview's color will be changed on all activities.

public class Text_Colour extends Activity implements RadioGroup.OnCheckedChangeListener {

RadioButton rb1, rb2, rb3, rb4;
TextView tv2;
RadioGroup rg1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.colours);

    tv2 = (TextView)findViewById(R.id.textview2);
    rb1 = (RadioButton) findViewById(R.id.radioButton1);
    rb2 = (RadioButton) findViewById(R.id.radioButton2);
    rb3 = (RadioButton) findViewById(R.id.radioButton3);
    rb4 = (RadioButton) findViewById(R.id.radioButton4);
    rg1 = (RadioGroup) findViewById(R.id.radiogroup1);
    rg1.setOnCheckedChangeListener(this);

}

public void onCheckedChanged(RadioGroup rg1, int r) {

    // TODO Auto-generated method stub
    if (r==rb1.getId()) {
        tv2.setTextColor(Color.RED); 
    } 
    if (r==rb2.getId()) {
        tv2.setTextColor(Color.YELLOW); 
    } 
    if (r==rb3.getId()) {
        tv2.setTextColor(Color.GREEN); 
    } 
    if (r==rb4.getId()) {
        tv2.setTextColor(Color.BLUE); 
    } 

    else {
        tv2.setTextColor(Color.BLACK);
    }

}

}

thanks for your time.

Ket
  • 273
  • 2
  • 8
  • 20

2 Answers2

1

If you are talking about one application and activities within it, then I would suggest to go with SharedPreferences. Here is what you need to do:

  1. When the radiobutton value is changed, save it in shared preferences.
  2. Make all your activities to listen for changes in SharedPreferences. In this case, as soon as you change a color, all running activities will be notified so they will update their UI. Just use SharedPreferences.registerOnSharedPreferenceChangeListener() method.
  3. onCreate of every activity needs to read the color value from shared preferences and do necessary UI work. Done!
ridoy
  • 6,274
  • 2
  • 29
  • 60
avepr
  • 1,865
  • 14
  • 16
1

If you want that a change in the radio buttons selection will update all TextViews' text colors in all of your activities, even the running ones, you should use a global variable which stores the color. Here is a nice example of creating global-like variables in Android, which are available to all of your application components.

Community
  • 1
  • 1
Jong
  • 9,045
  • 3
  • 34
  • 66