Android Custom View Constructor
Custom view is a common requirement in Android, and each custom view needs to implement three basic constructors, and these three constructors have two common ways of writing.
First Kind
Each constructor calls the constructor of the base class, and then calls a public initialization method for additional initialization.
public class MyView extends ListView {public
myview (context) {
super);
Sharedconstructor ();
}
Public MyView (context, AttributeSet attrs) {
Super (context, attrs);
Sharedconstructor ();
}
Public MyView (context, AttributeSet attrs, int defstyleattr) {
Super (context, attrs, defstyleattr);
Sharedconstructor ();
}
private void Sharedconstructor () {
//do some initialize work.
}
}
Second Kind
Cascade Invocation, each constructor calls a constructor with one more parameter, the last constructor calls the constructor of the base class, and finally does some extra initialization work.
public class MyView extends ListView {public
myview (context
, null);
Public MyView (context, AttributeSet attrs) {This
(context, attrs, 0);
}
Public MyView (context, AttributeSet attrs, int defstyleattr) {
Super (context, attrs, defstyleattr);
Other initialize work.
}
So the question is, which way should we use it?
The conclusion is: It's best to use the first one, because the second approach can be problematic in some cases, such as when your custom view inherits from ListView or TextView, ListView or TextView internal constructors have a default Defstyle, and the second method calls Defstyle passes in 0, which overrides the default Defstyle in the base class, resulting in a series of problems. Take ListView For example, and look at its constructor.
Public ListView {This
(context, NULL);
}
Public ListView (context, AttributeSet attrs) {This
(context, Attrs, Com.android.internal.r.attr.listviewstyle);
}
Public ListView (context, AttributeSet attrs, int defstyleattr) {This
(context, Attrs, defstyleattr, 0);
} Public
ListView (context, AttributeSet attrs, int defstyleattr, int defstyleres) {
Super (context, attrs , defstyleattr, defstyleres);
Other works.
}
You can see that a com.android.internal.r.attr.listviewstyle is passed in the second constructor code of ListView, and when we call with the second method (cascade), we pass in 0, which overrides this default value. But the first method calls super (context, attrs); This, in turn, invokes the base class of this (context, attrs, Com.android.internal.r.attr.listviewstyle);
Thank you for reading, I hope to help you, thank you for your support for this site!