Detailed introduction to the constructor of Android custom view

Constructor for Android custom view

Custom view is a common requirement in Android. Each custom view needs to implement three basic constructors, which can be written in two common ways.

First kind

Each constructor calls the constructor of the base class respectively, and then calls a public initialization method for additional initialization.

Second

Cascade call, each constructor calls the constructor with one more parameter than it, the last constructor calls the constructor of the base class, and finally does some additional initialization work.

So the question is, which way should we use?

The conclusion is: it is best to use the first method, because the second method may have problems in some cases. For example, when your custom view inherits from listview or textview, the constructor inside listview or textview will have a default defstyle. When the second method is called, defstyle will pass in 0, which will override the default defstyle in the base class, This leads to a series of problems. Take listview as an example to see its constructor.

You can see that a com.android.internal.r.attr.listviewstyle is passed in the second constructor code of listview. When using the second method (cascade) call, we pass in 0, which will override the default value. But the first method calls super (context, attrs). Then, this (context, com. Android. Internal. R.attr. Listviewstyle) of the base class is called; There will be no problem.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>