android-我的自定义视图的默认属性值(从LinearLayout继承)

我有一个自定义布局

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);
    ...
}

布局在xml中定义

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

然后我在其他布局中使用它

情况1

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

情况二

// 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 .../>

我的自定义布局PersonView如何实现案例2?

解决方法:

类似问题已在https://stackoverflow.com/a/25982512/3554436解决

将android:layout_margin添加到attrs.xml

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

像其他自定义属性一样访问属性

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);

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...