*
* @param choices the new list of choices.
*/
public void setChoices(List<String> choices) {
TextView textView = blip.getDocument();
FormView formView = textView.getFormView();
// Count existing choice elements
int existingCount = 0;
for (FormElement formElement : formView.getFormElements()) {
if (formElement.getType() == ElementType.LABEL &&
formElement.getName().startsWith(PREV_CHOICE_PREFIX) &&
formElement.getName().endsWith(PREV_CHOICE_LABEL_SUFFIX)) {
++existingCount;
}
}
// Prune extra choices
if (existingCount > choices.size()) {
for (int i = existingCount - 1; i >= choices.size(); --i) {
String choiceLabel = PREV_CHOICE_PREFIX + String.valueOf(i) + PREV_CHOICE_LABEL_SUFFIX;
int position = textView.getPosition(formView.getFormElement(choiceLabel));
// Delete the carriage return following the label.
textView.delete(new Range(position + 1, position + 2));
// Delete the label.
formView.delete(choiceLabel);
// Delete the radio button.
formView.delete(PREV_CHOICE_PREFIX + String.valueOf(i) + PREV_CHOICE_RADIO_SUFFIX);
}
existingCount = choices.size();
}
// Replace existing labels.
for (int i = 0; i < existingCount; ++i) {
String choiceLabel = PREV_CHOICE_PREFIX + String.valueOf(i) + PREV_CHOICE_LABEL_SUFFIX;
FormElement label = formView.getFormElement(choiceLabel);
if (!choices.get(i).equals(metadata.getChoices().get(i))) {
label.setValue(choices.get(i));
formView.replace(label);
}
}
// Add new labels.
if (existingCount < choices.size()) {
// Get the position of the last label.
int lastLabelPosition;
if (existingCount == 0) {
lastLabelPosition = textView.getPosition(formView.getFormElement(PREV_CHOICES_RADIOGROUP));
} else {
String choiceLabel = PREV_CHOICE_PREFIX + String.valueOf(existingCount - 1) +
PREV_CHOICE_LABEL_SUFFIX;
lastLabelPosition = textView.getPosition(formView.getFormElement(choiceLabel)) + 1;
}
for (int i = existingCount; i < choices.size(); ++i) {
FormElement radioButton = new FormElement(
ElementType.RADIO_BUTTON,