peter_budo peter_budo - 6 months ago 125
Android Question

Custom ListPreference with dynamic entries

I need dynamic entries in ListPreference so I can not use conventional way of XML setup of which there are tons of materials online. So far I have following setup as you can see bellow. Problem is that when I run this I see dialog with title and message but no entries are showed even though I know that entries and values are not empty (I know that my entries and values are same but I would get error if I didn't supplied entries)


my.preference.DynamicPreference
android:title="@string/date_format"
android:dialogMessage="@string/profile_info_date_format"
android:entryValues="@array/date_format_values"
android:entries="@array/date_format_values"



public class DynamicPreference extends ListPreference {
private int index;

public DynamicPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}

public DynamicPreference(Context context) {
super(context);
}

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
builder.setTitle(getTitle());
builder.setMessage(getDialogMessage());
builder.setSingleChoiceItems(entries(), -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
});
super.onPrepareDialogBuilder(builder);
}

@Override
public void setEntries(CharSequence[] sequence) {
CharSequence[] entries = listObjects().toArray(new CharSequence[listObjects().size()]);
super.setEntries(entries);
}

@Override
public void setEntryValues(CharSequence[] sequence) {
CharSequence[] values = getContext().getResources().getStringArray(R.string.date_format);
super.setEntryValues(values);
}
}

Answer

The android:dialogMessage was good starting point here, thank you @MH. for spotting it. Bellow is simple setup I ended with, I hope someone may find it helpful

<my.preference.DynamicPreference
        android:title="@string/local_time"
        android:key="profile_info_local_time"
        />

public class DynamicPreference extends ListPreference {


    public DynamicPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DynamicPreference(Context context) {
        super(context);
    }

    @Override
    protected View onCreateDialogView() {
        ListView view = new ListView(getContext());
        view.setAdapter(adapter());
        setEntries(entries());
        setEntryValues(entryValues());
        setValueIndex(initializeIndex());
        return view;
    }

    private ListAdapter adapter() {
        return new ArrayAdapter(getContext(), android.R.layout.select_dialog_singlechoice);
    }

    private CharSequence[] entries() {
        //action to provide entry data in char sequence array for list
    }

    private CharSequence[] entryValues() {
        //action to provide value data for list
    }
}