I have a question for the creator of Android custom view.

Asked 1 years ago, Updated 1 years ago, 139 views

I understand that if you inherit another layout when creating a custom view, you need to implement the creator below I wonder why the defStyleAttr and defStyleRes parameters are needed and used in what places.~ If possible, please let me know how to use it!

public MyView(Context context) {
    super(context);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

constructor software_development custom-view

2022-09-22 08:31

1 Answers

defStyleAttr is a parameter for specifying the basic properties of a view. If you look at the constructor code in EditText, you can see that it is defined as follows.

public class EditText extends TextView {
    public EditText(Context context) {
        this(context, null);
    }

    public EditText(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.editTextStyle);
    }

    public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public EditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    ...
}

If you look at the second constructor, you can see that this() calls the third constructor. com to defStyleAttr.The properties defined in android.internal.R.attr.editTextStyle are given as follows:

<style name="Widget.EditText">
    <item name="focusable">true</item>
    <item name="focusableInTouchMode">true</item>
    <item name="clickable">true</item>
    <item name="background">?attr/editTextBackground</item>
    <item name="textAppearance">?attr/textAppearanceMediumInverse</item>
    <item name="textColor">?attr/editTextColor</item>
    <item name="gravity">center_vertical</item>
    <item name="breakStrategy">simple</item>
    <item name="hyphenationFrequency">normal</item>
</style>

Although EditText inherits TextView, it would be easy to understand that EditText-specific attributes are set at the time of View creation through defStyleAttr. The difference between defStyleAttr and defStyleRes is the difference between R.attr.XXX and R.style.XXX.

Please refer to the link below for the relevant examples.

http://www.programering.com/a/MjNwATNwATg.html


2022-09-22 08:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.