У меня есть собственный компонент EditText (составной компонент на основе LinearLayout), и я использую несколько экземпляров в той же Деятельности. Пользовательский компонент работает, как ожидалось, однако, когда я поворачиваю ui, текст, который был введен во втором компоненте, внезапно копируется в первый компонент. В противном случае оба пользовательских компонента функционируют точно так, как ожидалось. Оба компонента имеют уникальный идентификатор в макете активности.Несколько экземпляров одного и того же компонента соединения андроида
Вот код для моего компонента клиента:
public class MyEditText extends LinearLayout{
private EditText mEditText;
TextView mTextCounter;
private int errorIconRes;
private String textHint;
private boolean showLength;
private int maxCount;
private int lines;
private boolean phoneField;
private String errorMessage;
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZipEditText, 0, 0);
phoneField = a.getBoolean(R.styleable.ZipEditText_phone, false);
errorIconRes = a.getInt(R.styleable.ZipEditText_icon_err, R.drawable.form_error_icon);
textHint = a.getString(R.styleable.ZipEditText_hint);
maxCount = a.getInt(R.styleable.ZipEditText_maxLength, 100);
lines = a.getInt(R.styleable.ZipEditText_lines, 1);
showLength = a.getBoolean(R.styleable.ZipEditText_showLength, false);
a.recycle();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.comp_zip_edittext, this, true);
mEditText = (EditText) v.findViewById(R.id.text_field);
mEditText.addTextChangedListener(getTextWatcher());
if (textHint!= null)mEditText.setHint(textHint);
mImageViewError = (ImageView) v.findViewById(R.id.icon_error);
mTextCounter = (TextView) v.findViewById((R.id.text_counter));
if (lines>1 && !phoneField) {
mEditText.setLines(lines);
mEditText.setSingleLine(false);
}
if (showLength) {
mTextCounter.setVisibility(View.VISIBLE);
mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxCount)});
mEditText.addTextChangedListener(getTextWatcherLength());
} else {
mTextCounter.setVisibility(View.GONE);
}
Вот файл макета моего пользовательского компонента:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal">
<EditText
android:id="@+id/text_field"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="left"
android:paddingLeft="10dp"
android:singleLine="true"
android:inputType="textNoSuggestions"
android:layout_alignParentTop="true"
/>
<ImageView
android:id="@+id/icon_error"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@drawable/form_error_icon"
android:layout_marginTop="10dp"
android:layout_marginRight="15dp"
android:layout_alignRight="@id/text_field"
android:layout_alignTop="@id/text_field"
android:visibility="gone"/>
</RelativeLayout>
<TextView
android:id="@+id/text_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:layout_gravity="right"
android:visibility="gone"/>
</LinearLayout>
А вот мой файл макета для деятельности:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:zip="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:background="@color/white" >
<TextView
android:id="@+id/error_msg"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="18sp"
android:textColor="@color/home_image_red"
android:background="@color/zip_error_gray"
android:text="Something went wrong"
android:visibility="gone"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:background="@color/white" >
<TextView
android:id="@+id/upsell"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="18sp"
android:text="Sign in to use all our features."
/>
<com.myproject.android.components.MyEditText
android:id="@+id/request_phone"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="5dp"
android:gravity="left"
android:singleLine="true"
zip:phone="true"
zip:hint="@string/hint_phone"/>
<com.myproject.android.components.MyEditText
android:id="@+id/request_comments"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="5dp"
android:gravity="left"
zip:lines="3"
zip:maxLength="120"
zip:showLength="true"
zip:hint="@string/hint_comments"/>
<CheckBox
android:id="@+id/checkbox_request_visit"
style="@style/contact_label"
android:layout_centerInParent="true"
android:text="@string/check_home_visit"
android:checked="false" />
<Button
android:id="@+id/request_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:text="Request a Showing"
android:textColor="@color/pbz_button_primary_foreground_color"
android:textStyle="bold"
android:background="@drawable/button_registration"
android:gravity="center"/>
<TextView
android:id="@+id/terms_link"
style="@style/FinePrint"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center_horizontal"
android:paddingBottom="5dp"
android:text="@string/request_showing_terms"
/>
</LinearLayout>
</LinearLayout>
«Оба компонента имеют уникальный идентификатор в макете деятельности» - да, но виджеты внутри ваших компонентов этого не делают. – CommonsWare
Hi CommonsWare, я знаю об этом. Однако, как бы я дал им пользовательские идентификаторы? что это возможно? А если нет, то подразумевается, что я не могу использовать несколько экземпляров составного компонента в одной активности? – dizzle
«Это возможно?» - вы можете называть 'setId()' на них. В Android есть какое-то место, где вы можете создать для них отдельный идентификатор вида, но я не помню, как это было на моей голове. Или, реализуйте 'onSaveInstanceState()' и 'onRestoreInstanceState()' в своем пользовательском 'View', чтобы самостоятельно управлять уникальностью состояния. – CommonsWare