我正在学习使用以下自定义视图的信息:

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

描述说:

一如既往的类初始化,超级被称为首先。此外,这不是默认构造函数,而是一个参数化的构造函数。当这些参数从XML布局文件中夸大时,将使用这些参数创建EDITTEXT,因此,我们的构造函数也需要将它们带入并将其传递给超类构造函数。

有更好的描述吗?我一直在尝试弄清楚构造函数的外观,并提出了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);
} 
有帮助吗?

解决方案

您不需要第一个,因为那是行不通的。

第三个将意味着您的习俗 View 可以从XML布局文件中使用。如果您不在乎,就不需要它。

第四个完全是错的,阿法克。没有 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
}

您可以在 这本书的例子.

其他提示

这是我的模式(创建自定义 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>

当您添加自定义时 Viewxml 像 :

 <com.mypack.MyView
      ...
      />

您将需要 公共构造师 MyView(Context context, AttributeSet attrs), 否则您会得到一个 Exception 什么时候 Android 尝试 inflate 您的 View.

当您添加您的 Viewxml 并且 指定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);
    }

看到这个

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top