Obtener valor de botón de opción agregado mediante programación del grupo de radio en diseño lineal
-
21-12-2019 - |
Pregunta
Estoy tratando de obtener el valor de un botón de opción que agrego a un grupo de opción y que se agrega a un diseño lineal, y luego llamo a la clase desde mi actividad.Este es mi código:
MultiChoice.java
public class MultipleChoice {
Context context;
List<String> choice_values;
String hint;
public MultipleChoice (Context context, String hint, List<String> choice_value_array){
choice_values = new ArrayList<String>();
this.context = context;
this.choice_values = choice_value_array;
this.hint = hint;
}
public View createRadioGroup(){
LinearLayout llContainer = new LinearLayout(context);
llContainer.setOrientation(LinearLayout.VERTICAL);
llContainer.addView(hintTextView());
llContainer.addView(radioButtons());
return llContainer;
}
private TextView hintTextView() {
// TODO Auto-generated method stub
TextView tvHint = new TextView(context);
tvHint.setText(hint);
return tvHint;
}
private RadioGroup radioButtons() {
// TODO Auto-generated method stub
RadioGroup rbGroup = new RadioGroup(context);
rbGroup.setOrientation(RadioGroup.VERTICAL);
for (String value : choice_values){
RadioButton rbValue = new RadioButton(context);
rbGroup.addView(rbValue);
rbValue.setText(value);
}
return rbGroup;
}
}
Así creo el control en mi actividad:
LinearLayout template_container = (LinearLayout) findViewById(R.id.llTemplate);
MultipleChoice mcControl = new MultipleChoice(getApplicationContext(), parts[0], choices);
control = mcControl.createRadioGroup();
template_container.addView(control);
He intentado algo como esto, pero no estoy seguro de estar intentando el enfoque correcto ya que no funciona:
View child = template_container.getChildAt(i);
LinearLayout v = ((LinearLayout)child);
View rgView = v.getChildAt(1);
RadioGroup rg = ((RadioGroup)rgView);
El RadioGroup
se agrega y se muestra bien.Todo lo que quiero hacer es obtener el valor del botón de opción seleccionado.¡Gracias de antemano!
EDITAR
Así es como obtengo el valor de un EditText
y funciona bien.
Obtengo el control y lo agrego a una Lista que contiene Vistas y luego hago esto con él para obtener el valor si la vista contiene un EditText
:
String text = ((EditText)view).getText().toString().trim();
Solución 4
Resolví el problema agregando un oyente onCheckChanged a los botones de opción en el momento de la creación y luego guardé el valor seleccionado en las preferencias compartidas.Cuando necesitaba los valores, simplemente obtuve todas las preferencias compartidas iterando a través de los identificadores que usé como clave en las preferencias compartidas.Mi código:
private RadioGroup radioButtons(final int radio_id) {
// TODO Auto-generated method stub
RadioGroup rbGroup = new RadioGroup(context);
rbGroup.setOrientation(RadioGroup.VERTICAL);
for (final String value : choice_values) {
RadioButton rbValue = new RadioButton(context);
rbGroup.addView(rbValue);
rbValue.setText(value);
rbValue.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
savePreferences("" + radio_id, value);
}
});
}
return rbGroup;
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
Y obteniendo los valores:
int radio_check = 0;
for (View view : addedControls) {
String entered_value = getControlValue(view, radio_check);
radio_check++;
}
En mi método getValue():
text = loadSavedPreferences("" + (radio_check));
Método LoadPrefs:
private String loadSavedPreferences(String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sharedPreferences.getString(key, "Default");
return name;
}
Otros consejos
Esto puede ser realmente útil:http://developer.android.com/guide/topics/ui/controls/radiobutton.html#HandlingEvents
Es posible que necesite agregar un id
a sus botones de radio.
Puede configurar una identificación en el botón de opción mediante programación.Por favor consulte aquí
Androide:View.setID(int id) mediante programación: ¿cómo evitar conflictos de ID?
Y luego use findviewbyId para obtener el botón de opción
Puedes probar esto:Primero agregue una identificación al grupo de radio usando:android:id="@+id/grupo de radio"
RadioGroup rbGroup = (RadioGroup)findViewById(R.id.radiogroup);
int RadioButtonId=rbGroup.getCheckedRadioButtonId();
View radioButton = rbGroup.findViewById(RadioButtonId);
String = Integer.toString(rbGroup.indexOfChild(radioButton)+1);
También puedes agregar ID mediante programación usando:
View.setId(int id);