FormFieldWrapper.java

 1package eu.siacs.conversations.ui.forms;
 2
 3import android.content.Context;
 4import android.text.SpannableString;
 5import android.text.style.ForegroundColorSpan;
 6import android.text.style.StyleSpan;
 7import android.view.LayoutInflater;
 8import android.view.View;
 9
10import java.util.List;
11
12import eu.siacs.conversations.R;
13import eu.siacs.conversations.ui.util.StyledAttributes;
14import eu.siacs.conversations.xmpp.forms.Field;
15
16public abstract class FormFieldWrapper {
17
18	protected final Context context;
19	protected final Field field;
20	protected final View view;
21	OnFormFieldValuesEdited onFormFieldValuesEditedListener;
22
23	FormFieldWrapper(Context context, Field field) {
24		this.context = context;
25		this.field = field;
26		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
27		this.view = inflater.inflate(getLayoutResource(), null);
28		String label = field.getLabel();
29		if (label == null) {
30			label = field.getFieldName();
31		}
32		setLabel(label, field.isRequired());
33	}
34
35	public final void submit() {
36		this.field.setValues(getValues());
37	}
38
39	public final View getView() {
40		return view;
41	}
42
43	protected abstract void setLabel(String label, boolean required);
44
45	abstract List<String> getValues();
46
47	protected abstract void setValues(List<String> values);
48
49	abstract boolean validates();
50
51	abstract protected int getLayoutResource();
52
53	abstract void setReadOnly(boolean readOnly);
54
55	protected SpannableString createSpannableLabelString(String label, boolean required) {
56		SpannableString spannableString = new SpannableString(label + (required ? " *" : ""));
57		if (required) {
58			int start = label.length();
59			int end = label.length() + 2;
60			spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, 0);
61			spannableString.setSpan(new ForegroundColorSpan(StyledAttributes.getColor(context,R.attr.colorAccent)), start, end, 0);
62		}
63		return spannableString;
64	}
65
66	protected void invokeOnFormFieldValuesEdited() {
67		if (this.onFormFieldValuesEditedListener != null) {
68			this.onFormFieldValuesEditedListener.onFormFieldValuesEdited();
69		}
70	}
71
72	public boolean edited() {
73		return !field.getValues().equals(getValues());
74	}
75
76	public void setOnFormFieldValuesEditedListener(OnFormFieldValuesEdited listener) {
77		this.onFormFieldValuesEditedListener = listener;
78	}
79
80	protected static <F extends FormFieldWrapper> FormFieldWrapper createFromField(Class<F> c, Context context, Field field) {
81		try {
82			F fieldWrapper = c.getDeclaredConstructor(Context.class, Field.class).newInstance(context,field);
83			fieldWrapper.setValues(field.getValues());
84			return fieldWrapper;
85		} catch (Exception e) {
86			e.printStackTrace();
87			return null;
88		}
89	}
90
91	public interface OnFormFieldValuesEdited {
92		void onFormFieldValuesEdited();
93	}
94}