How do I get the attribute value "required" in my Activity Class?
1. values\attrs.xml
<declare-styleable name="EditText">
<attr name="required" format="boolean" />
</declare-styleable>
2. layout\text.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.mycompany.test"
android:baselineAligned="false"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTest"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="text"
custom:required="true" />
Tools attributes reference. Android Studio supports a variety of XML attributes in the tools namespace that enable design-time features (such as which layout to show in a fragment) or compile-time behaviors (such as which shrinking mode to apply to your XML resources).
Create an XML res/values/attrs.xml file to define new attributes alongwith their data type. Create src/DateView.java file and add the code to define your custom component.
Design-time view attributes Android Studio supports a variety of XML attributes in the tools namespace that enable design-time features (such as which layout to show in a fragment) or compile-time behaviors (such as which shrinking mode to apply to your XML resources).
Note: These attributes don't work for ListView in Android Studio 2.2, but this is fixed in 2.3 ( issue 215172 ). Intended for: Any root <View> in a layout that's referred to by an <include>
In EditText constructor add logic to read data from xml:
public EditText(final Context context, final AttributeSet attrs, final int defStyle)
{
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditText);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.EditText_required: {
if (context.isRestricted()) {
throw new IllegalStateException("The "+getClass().getCanonicalName()+":required attribute cannot "
+ "be used within a restricted context");
}
boolean defaultValue = false;
final boolean required = a.getBoolean(attr, defaultValue );
//DO SOMETHING
break;
}
default:
break;
}
}
a.recycle();
}
The switch construct was used to check for many custom attributes. If you are only interested in one attribute you can skip switch statement
If you want to learn more, especially how to add method handler using xml attribute read this: Long press definition at XML layout, like android:onClick does
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