32

Buenos días, amigos. Tengo una actividad de preferencia, se llena desde un archivo XML. Cuando presionamos un elemento, deberíamos iniciar una nueva actividad. ¿Cómo hacerlo? ¿Qué debo escribir en XML-file o en la clase Java?Lanzar nueva actividad desde PreferenceActivity

Respuesta

59

Después de agregar preferencias utilizando

addPreferencesFromResource(R.xml.preferences); 

encontrar su preferencia que desea establecer onClick usando

findPreference("foo_bar_pref"); 

y definirlo por colada como

Preference fooBarPref = (Preference) findPreference("foo_bar_pref"); 

Entonces yo u puede configurar fácilmente su onClick usando

fooBarPref.setOnPreferenceClickListener (new OnPreferenceClickListener()){...} 

Usted puede comenzar su nueva actividad (usando un Intento) dentro de ese oyente.

+0

Gracias, muy útil respuesta! – QuickNick

+0

Su bienvenida. :) Supongo que deberías votar y verificar la pregunta como respondida. – faradaj

+0

Soy novato, ¿dónde están estas opciones? (He comprobado que tu respuesta es útil). – QuickNick

0

Debe registrar un onClickListener en la vista en la que desea iniciar la actividad. Luego, dentro de este método, solo necesita invocar la actividad con un intento. Algo como esto:

Intent intent = new Intent(this, ActivityToLaunch.class); 

// Start boardgame 
startActivity(intent); 
+0

¡Es elemental, pero gracias de todos modos! :) – QuickNick

12

Este es un buen tutorial para agregar preferencias dinámicamente ... después tiene que personalizarlo a su manera.

En XML:

<Preference android:key="key" android:title="See Android Market"></Preference> 

En la clase de Java:

Preferences preferences=findPreference("key"); 
       preferences.setIntent(new Intent(Intent.ACTION_VIEW,Uri.parse("https://market.android.com/"))); 

O

import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.preference.CheckBoxPreference; 
import android.preference.DialogPreference; 
import android.preference.Preference; 
import android.preference.PreferenceActivity; 
import android.preference.PreferenceCategory; 
import android.preference.PreferenceScreen; 
import android.widget.LinearLayout; 
import android.widget.ListView; 

public class SettingsActivity extends PreferenceActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    /* Some initializations */ 
    LinearLayout layout = new LinearLayout(this); 
    layout.setOrientation(LinearLayout.VERTICAL); 

    ListView listView = new ListView(this); 
    listView.setId(android.R.id.list); 
    listView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 1)); 
    layout.addView(listView); 

    this.setContentView(layout); 
    /* Preferences time! (we build the preferences) */ 
    Preference version = getPreference("My School Manager", "Version 2.0",null); 
    Preference author = getPreference("Author", "Balu", null); 
    Preference marketLink = getPreference("Android market","View all my apps :)",new Intent(Intent.ACTION_VIEW, Uri.parse("http://market.android.com/"))); 

    CheckBoxPreference check = new CheckBoxPreference(this); 
    check.setTitle("Checkbox"); 
    check.setSummary("Example of checkbox"); 
    DialogPreference license = new MyDialogPreference(this, "License","This is the license for...bla bla"); 

    /* Now we add the preferences to the preference screen */ 
    PreferenceScreen preferenceScreen = this.getPreferenceManager() 
      .createPreferenceScreen(this); 
    addPreferenceCategory(preferenceScreen, "Preferences Tutorial",version, author, marketLink, check, license); 
    this.setPreferenceScreen(preferenceScreen); 
} 
private boolean addPreferenceCategory(PreferenceScreen preferenceScreen, 
     String titleCategory, Preference... preferences) { 
    boolean addPreference = false; 
    for (Preference preference : preferences) { 
     if (preference != null) 
      addPreference = true; 
    } 
    if (addPreference) { 
     PreferenceCategory preferenceCategory = new PreferenceCategory(this); 
     preferenceCategory.setTitle(titleCategory); 
     preferenceScreen.addPreference(preferenceCategory); 
     for (Preference preference : preferences) { 
      if (preference != null) 
       preferenceCategory.addPreference(preference); 
     } 
     return true; 
    } else 
     return false; 
} 
private Preference getPreference(String title, String summary, Intent intent) { 
    Preference pref = new Preference(this); 
    pref.setTitle(title); 
    pref.setSummary(summary); 
    if (intent != null) 
     pref.setIntent(intent); 
    return pref; 
} 

public class MyDialogPreference extends DialogPreference { 
    public MyDialogPreference(Context context, String title, String text) { 
     super(context, null); 
     this.setTitle(title); 
     this.setDialogMessage(text); 
    } 
} 

}

+1

Me gusta esta primera opción mejor que la respuesta aceptada, ya que es más limpio simplemente usar el "setIntent" en la preferencia. – Josh

68

Teniendo en cuenta que está utilizando preferencias XML puede agregar código a la derecha en el xml:

<Preference 
    android:title="Some Title" 
    android:summary="Some Description"> 

    <intent 
     android:action="android.intent.action.VIEW" 
     android:targetPackage="com.package.name" 
     android:targetClass="com.package.name.ActivityName" 
    /> 

</Preference> 
+19

Para aquellos que obtienen 'ActivityNotFoundException' s aquí después de tratar de iniciar su actividad en las preferencias, es posible que esté utilizando nombres de subpaquetes de forma incorrecta, como yo estaba haciendo. Si ese es el caso, use solo subpaquetes en la sección targetClass. '' – Andrew

+0

To tal vez le salve la pena a algunas personas: puede definir categorías y datos adicionales en etiquetas XML dentro de , pero NO PUEDE establecer banderas de intención usando XML. Si desea establecer indicadores, debe registrar un OnPreferenceClickListener y ejecutar el Intent manualmente. – rjh

+1

usuarios de Gradle, si declaraste un 'applicationId' en tu build.gradle, ¡mi solución puede ayudarte! http://stackoverflow.com/a/27053915/499125 –

12

Gradle Builders, ¡mire aquí!

Si está utilizando gradle over ant como herramienta de compilación, y declaró applicationId dentro de android.

[build.gradle]: 

android { 
    defaultConfig { 
     ... 
     applicationId "com.overriding.package.name" 
    } 
    ... 
} 

Esto sobrescribirá cualquier valor declarado en el AndroidManifest.xml 's android:package como identificador único de su aplicación!

[AndroidManifest.xml] 

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.my.package"> 
    <activity android:name=".settings.MyActivity"/> 
</manifest> 

El <intent> tendría que tomar los dos nombres de los paquetes en cuenta!

<Preference 
    android:title="Some Title" 
    android:summary="Some Description"> 

    <intent 
     android:targetPackage="com.overriding.package.name" 
     android:targetClass="com.my.package.settings.MyActivity/> 
</Preference> 
+0

Usted, señor, merece cada litro de amor que este planeta es capaz de producir. –

+1

Entonces necesitaré muchos tarros para llenar. –

Cuestiones relacionadas