0

Can't seem to find any non-deprecated (HONEYCOMB+) examples showing how to add dynamically created preferences to a preferencefragment instead of using an xml resource that predefined the form fields.

Specifically I'm trying to create a list of check-boxes with Bluetooth devices that have been paired with the phone. Using mBluetoothAdapter.getBondedDevices() and presumably the CheckBoxPreference.

class GeneralPreferenceFragment extends PreferenceFragment {
    private Context context = getBaseContext();
    private int i;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //get Bluetooth Adapter
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            SharedPreferences prefs = context.getSharedPreferences("bt_devices", 0);
            this.i = 0;

            for (BluetoothDevice device : pairedDevices) {
                CheckBoxPreference checkBoxPreference = new CheckBoxPreference(context);
                checkBoxPreference.setKey("btDevice_"+this.i);
                checkBoxPreference.setChecked(prefs.getBoolean("btDevice_"+this.i, false));
                this.i++;
                //(Somehow add CheckboxPreference to PreferenceFragment)
            }// end for loop
        }// end if(paired devices)
    }// end onCreate()
} // end PreferenceFragment

Any advice would be greatly appreciated.

1 Answers1

0

Figured it out. Define stuff in onViewCreated() instead of in onCreate().

Search programmatically adding adding preferences to preference fragment. Here's one example How do I programmatically add EditTextPreferences to my PreferenceFragment?

Community
  • 1
  • 1