The default attribute values ​​for my custom view (inherited from LinearLayout)

I have my own layout

public class PersonView extends LinearLayout{

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

public PersonView(Context context) {
    super(context);
    initUi(context);
}

    private void initUi(Context context){
    LayoutInflater.from(context).inflate(R.layout.person_view, this, true);
    profilePicture = (ImageView)findViewById(R.id.profile_picture);
    ...
}

Layout is defined in xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">
   ...

Then i use it in another layout

Case 1

// In this case android:layout_margin is specified so it should be used
<my.package.PersonView android:layout_margin="10dp" .../>

Case 2

// In this case android:layout_margin is NOT specified so I want for my PersonView some default value should be used (say 5pt)
<my.package.PersonView .../>

What should I do for my custom PersonView layout to achieve Case 2?

+3
source share
1 answer

A similar problem was resolved at fooobar.com/questions/409643 / ...

Add android:layout_margintoattrs.xml

<declare-styleable name="PersonView">
    ...
    <attr name="android:layout_margin" />
    ...
</declare-styleable>

Access to the attribute, like other user attributes:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PersonView);
float margin = a.getDimension(R.styleable.PersonView_android_layout_margin, 0);
...
boolean hasMargin = a.hasValue(R.styleable.PersonView_android_layout_margin);
+1
source

Source: https://habr.com/ru/post/1794707/


All Articles