Junior — Middle
How can custom properties be defined in a user Android component?
sobes.tech AI
Answer from AI
In Android, to define custom properties of a user component, XML attributes are usually used, which are described in the attrs.xml file located in the res/values folder.
Example:
- Create a file
res/values/attrs.xmland define your attributes:
<resources>
<declare-styleable name="MyCustomView">
<attr name="customColor" format="color" />
<attr name="customSize" format="dimension" />
</declare-styleable>
</resources>
- In your custom component (for example, a subclass of
View), read these attributes in the constructor withContextandAttributeSetparameters:
public class MyCustomView extends View {
private int customColor;
private float customSize;
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
customColor = a.getColor(R.styleable.MyCustomView_customColor, Color.BLACK);
customSize = a.getDimension(R.styleable.MyCustomView_customSize, 16f);
a.recycle();
}
}
- These attributes can be used in XML layout:
<com.example.MyCustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customColor="#FF0000"
app:customSize="24sp" />
Thus, you create your own properties that can be set in XML and used in the component's code.