I am creating a custom compound view with the following layout
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:singleLine="true"/>
</merge>
As you can see, it is simply a TextView
and a EditText
. I want to be able to provide attributes to my custom view that are forwarded on to either the TextView
or EditText
. For example
<codeguru.labelededittext.LabeledEditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:label="@string/label"
app:hint="@string/hint"/>
I have figured out how to forward these string attributes to the TextView
and EditText
, repsectively:
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LabeledEditText,
0, 0);
try {
label.setText(a.getString(R.styleable.LabeledEditText_label));
edit.setHint(a.getString(R.styleable.LabeledEditText_hint));
} finally {
a.recycle();
}
Now I also want to set the inputType
of the EditText
. If I create a <attr name="inputType" format="flag">
tag, will I have to populate it with all the possible flag values? Is there a way to reuse the values already declared by EditText
?
To efficiently reuse complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts. For example, a yes/no button panel, or custom progress bar with description text.
An <attr> element has two xml attributes name and format . name lets you call it something and this is how you end up referring to it in code, e.g., R. attr. my_attribute . The format attribute can have different values depending on the 'type' of attribute you want.
Custom Views is just a way to make an android developer a painter. When you need to create some custom and reuse the views when it is not provided by the Android Ecosystem. Custom Views can be used as widgets like TextView, EditText etc.
You can get this with:
int[] values = new int[]{android.R.attr.inputType};
TypedArray standardAttrArray = getContext().obtainStyledAttributes(attrs, values);
try {
mInputType = standardAttrArray.getInt(0, EditorInfo.TYPE_NULL);
} finally {
standardAttrArray.recycle();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With