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