【问题标题】:Default attribute values for my custom view (inherited from LinearLayout)我的自定义视图的默认属性值(继承自 LinearLayout)
【发布时间】:2011-02-25 12:40:50
【问题描述】:

我有一个自定义布局

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

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

案例一

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

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

我的自定义布局 PersonView 应该怎么做才能实现案例 2?

【问题讨论】:

  • 对于 PersonView 我想定义一组默认属性。
  • 你有没有想过这个问题?我想出的唯一解决方案是以编程方式检查自定义视图的构造函数以查看是否已设置属性,如果未将其设置为默认值。这感觉不对,并且默认属性(显然)不会显示在图形视图设计器中。
  • 还想知道如何做到这一点 - 任何进一步的消息?

标签: android attributes custom-controls


【解决方案1】:

类似问题已在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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2011-01-31
    • 2011-03-09
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多