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.xmpp.forms.Field;
14
15public abstract class FormFieldWrapper {
16
17	protected final Context context;
18	protected final Field field;
19	protected final View view;
20
21	protected FormFieldWrapper(Context context, Field field) {
22		this.context = context;
23		this.field = field;
24		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
25		this.view = inflater.inflate(getLayoutResource(), null);
26		String label = field.getLabel();
27		if (label == null) {
28			label = field.getFieldName();
29		}
30		setLabel(label, field.isRequired());
31	}
32
33	public final void submit() {
34		this.field.setValues(getValues());
35	}
36
37	public final View getView() {
38		return view;
39	}
40
41	protected abstract void setLabel(String label, boolean required);
42
43	abstract List<String> getValues();
44
45	abstract boolean validates();
46
47	abstract protected int getLayoutResource();
48
49	protected SpannableString createSpannableLabelString(String label, boolean required) {
50		SpannableString spannableString = new SpannableString(label + (required ? " *" : ""));
51		if (required) {
52			int start = label.length();
53			int end = label.length() + 2;
54			spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, 0);
55			spannableString.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.accent)), start, end, 0);
56		}
57		return spannableString;
58	}
59
60	protected static <F extends FormFieldWrapper> FormFieldWrapper createFromField(Class<F> c, Context context, Field field) {
61		try {
62			return c.getDeclaredConstructor(Context.class, Field.class).newInstance(context,field);
63		} catch (Exception e) {
64			e.printStackTrace();
65			return null;
66		}
67	}
68}