How to add a button to a PreferenceScreen? How to add a button to a PreferenceScreen? android android

How to add a button to a PreferenceScreen?


For the xml:

<Preference    android:title="Acts like a button"    android:key="@string/myCoolButton"    android:summary="This is a cool button"/>

Then for the java in your onCreate()

Preference button = findPreference(getString(R.string.myCoolButton));button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {    @Override    public boolean onPreferenceClick(Preference preference) {         //code for what you want it to do         return true;    }});

This will appear like a normal Preference, with just a title and a summary, so it will look like it belongs.


I suppouse its too late.This is what i have done for a Button Preference.

The preference in preference.xml file in xml folder

....    <Preference        android:key="resetBD"        android:title="@string/ajustes_almacenamiento"        android:summary="@string/ajustes_almacenamiento_desc"        android:widgetLayout="@layout/pref_reset_bd_button"     ></Preference>  ...

and pref_reset_bd_button.xml in layout folder

 <?xml version="1.0" encoding="utf-8"?>   <Button       xmlns:android="http://schemas.android.com/apk/res/android"        android:id="@+id/resetButton"         android:text="@string/ajustes_almacenamiento_bt"         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="resetearBD">   </Button>


I wanted to add an Exit link to the preferences and was able to modify Jakar's code to make it work like this:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >      <PreferenceCategory android:title="Settings">       <Preference android:title="Click to exit" android:key="exitlink"/>          </PreferenceCategory>    </PreferenceScreen>

Originally the 'Preference' was a 'EditTextPreference' which I hand edited.

Then in the class:

public class MyPreferences extends PreferenceActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    addPreferencesFromResource(R.xml.mypreferences);    Preference button = (Preference)getPreferenceManager().findPreference("exitlink");          if (button != null) {        button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {            @Override            public boolean onPreferenceClick(Preference arg0) {                finish();                   return true;            }        });         }}}