Agregar preferencias dinámicas de la casilla de verificación en Android y mostrarlas en la pantalla de preferencias?

Quiero implementar la funcionalidad donde el usuario será capaz de seleccionar qué grupo de elementos que se muestran con las preferencias compartidas de casilla de verificación. Para ser más precisos leeré los elementos seleccionados de las preferencias y la pantalla.

Aquí está mi clase de preferencias

public class Preferences extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //One way to add default preferences //addPreferencesFromResource(R.xml.prefs); //For now I prefer this setPreferenceScreen(defaultPref()); } // The first time application is launched this should be read private PreferenceScreen defaultPref() { PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); CheckBoxPreference checkboxPref = new CheckBoxPreference(this); checkboxPref.setKey("1"); checkboxPref.setTitle("SomeRandomStuff"); root.addPreference(checkboxPref); return root; } public showAllPreferences () { // TO SHOW ALL THE PREFERENCES BUT NOT SURE HOW TO DISPLAY THEM } } 

Ahora no puedo entender cómo puedo añadir más preferencias dinámicamente y mostrarlas en la pantalla de preferencias.

Aquí está la clase de actividad principal

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.main); }catch (Exception e) { e.printStackTrace(); } exView = (ExpandableListView) findViewById(R.id.expandableListView1); // STUFF TO ADD IN PREFERENCES editText = (EditText) findViewById(R.id.editText1); //BUTTON TO ADD PREFERENCES.(SEARCH TERM IS IDENTIFIED AND ADDED TO PREF) addButton = (ImageButton) findViewById(R.id.imageButton1); // BUTTON TO DISPLAY PREFERENCES prefButton = (ImageButton) findViewById(R.id.imageButtonPref); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences.Editor editor = settings.edit(); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub PrefObject obj = new PrefObject(); String key = Integer.toString(i); String title = editText.getText().toString(); //prefArray.add(obj); editor.putString(key, title); editor.commit(); i++ } }); prefButton.setOnClickListener(new OnClickListener() { // This method should show the preferences activity with new data @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(Main.this, Preferences.class); startActivity(intent); // I know how to call the intent but I am not sure if // how to read the saved contents and display it Preferences pref = new Preferences(); pref.showAllPreferences(); } }); 

AFAIK, no hay opción de "visibilidad" para las preferencias, lo cual tiene sentido cuando crees que es todo un ListView.

Véase [ 1 ]. Por lo que veo, podrías hacer algo como esto:

 PreferenceScreen screen = this.getPreferenceScreen(); // Use "1" since you're using "1" to create it. CheckBoxPreference ckbox = (CheckBoxPreference) this.findPreference("1"); screen.removePreference(ckbox); 

Para recrear, usted podría hacer esto [ 2 ]:

 screen.addPreference(ckbox); 

Además, recuerde crear su preferencia usando el setOrder(int order) para que al recrear, se vuelva a crear en la posición correcta.

Como puede ver, podría valer la pena mantener una referencia global a la preferencia para hacerlo más fácil y más rápido.

Por supuesto, no necesito decir que debes integrar esa lógica en tu escucha de CheckboxPreference. Ver esta respuesta de nadie más que Reto Meier a sí mismo para ver una buena manera de hacerlo (es una casilla de verificación, también). Allí registra un oyente en toda la pantalla y comprueba qué preferencia activa el oyente, pero puede hacerlo más sencillo (pero más detallado más adelante) simplemente estableciendo su setOnPreferenceChangeListener .

* Editar: Veo que también está usando un botón para agregar la preferencia. También puede implementar la misma lógica anterior en el propio botón. Todo depende si usted quiere hacer esto usando una casilla de verificación o un botón.

Por último, podría valer la pena simplemente establecer el estado habilitado, a menos que esté haciendo algo como "ver preferencias avanzadas" o algo valioso para mantener a los usuarios novatos lejos de hacer cosas peligrosas a su aplicación. Pero generalmente los estados de habilitación funcionan mejor para la experiencia del usuario, IMHO.

Espero que esto responda tu pregunta.

  • Inicie la aplicación de Android con actividad específica
  • OnSavedInstanceState vs. SharedPreferences
  • Android getDefaultSharedPreferences
  • Perder algunos valores usando getStringSet y putStringSet
  • Android Menu sólo funciona una vez por ejecución de aplicación
  • Guardar paquete con SharedPreferences
  • Guardar tabla de objetos personalizados en Preferencias compartidas
  • Las preferencias compartidas de Android no funcionan
  • Uso de las preferencias compartidas para un ahorro de alto valor
  • Conversión de JSONArray a matriz normal
  • ¿Pueden las preferencias compartidas ser privadas?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.