Android自定义视图构造函数

时间:2010-05-21 18:17:43

标签: xml android custom-view

我正在学习如何使用以下自定义视图:

http://developer.android.com/guide/topics/ui/custom-components.html#modifying

描述说:

  

类初始化和往常一样   超级被称为第一。此外,   这不是默认构造函数,但是   一个参数化的。 EditText是   用它们创建这些参数   从XML布局文件中膨胀,   因此,我们的构造函数需要两者   带走他们并将他们传递给   超类构造函数。

有更好的描述吗?我一直试图弄清楚构造函数应该是什么样子,我想出了4种可能的选择(参见帖子末尾的例子)。我不确定这4个选择是做什么(或不做什么),为什么要实现它们,或者参数意味着什么。有这些的描述吗?

public MyCustomView()
{
    super();
}

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

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

public MyCustomView(Context context, AttributeSet attrs, Map params)
{
    super(context, attrs, params);
} 

3 个答案:

答案 0 :(得分:64)

你不需要第一个,因为它不起作用。

第三个意味着您的自定义View可用于XML布局文件。如果你不关心它,你就不需要它了。

第四个是错的,AFAIK。没有View构造函数将Map作为第三个参数。有一个int作为第三个参数,用于覆盖小部件的默认样式。

我倾向于使用this()语法来组合这些:

public ColorMixer(Context context) {
    this(context, null);
}

public ColorMixer(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ColorMixer(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // real work here
}

您可以在this book example中看到其余代码。

答案 1 :(得分:11)

这是我的模式(在这里创建自定义ViewGoup,但仍然):

// CustomView.java

public class CustomView extends LinearLayout {

    public CustomView(Context context) {
        super(context);
        init(context);
    }

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

    public CustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context ctx) {
        LayoutInflater.from(ctx).inflate(R.layout.view_custom, this, true);
            // extra init
    }

}

// view_custom.xml

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

答案 2 :(得分:7)

当您从View添加自定义xml时:

 <com.mypack.MyView
      ...
      />

您将需要公共构造函数 MyView(Context context, AttributeSet attrs),,否则当Exception尝试Android inflate View时,您将获得View

当您从xml添加android:style并且指定时,attribute <com.mypack.MyView style="@styles/MyCustomStyle" ... /> 就像:

MyView(Context context, AttributeSet attrs,int defStyle)

您还需要第三个公共构造函数 style

第三个构造函数通常在扩展样式并自定义时使用,然后您希望将View设置为布局中的给定public MyView(Context context, AttributeSet attrs) { //Called by Android if <com.mypack.MyView/> is in layout xml file without style attribute. //So we need to call MyView(Context context, AttributeSet attrs, int defStyle) // with R.attr.customViewStyle. Thus R.attr.customViewStyle is default style for MyView. this(context, attrs, R.attr.customViewStyle); }

修改详情

{{1}}

See this

相关问题