When creating a custom view, I have noticed that many people seem to do it like this:
public MyView(Context context) {
super(context);
// this constructor used when programmatically creating view
doAdditionalConstructorWork();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// this constructor used when creating view through XML
doAdditionalConstructorWork();
}
private void doAdditionalConstructorWork() {
// init variables etc.
}
My first question is, what about the constructor MyView(Context context, AttributeSet attrs, int defStyle)? I'm not sure where it is used, but I see it in the super class. Do I need it, and where is it used?
There's another part to this question.
Long story short, No, but if you do override any constructor, then ensure to call super(...) with the exact same number of arguments (like, see Jin's answer for example why).
If you will add your custom View from xml also like :
<com.mypack.MyView
...
/>
you will need the constructor public MyView(Context context, AttributeSet attrs), otherwise you will get an Exception when Android tries to inflate your View.
If you add your View from xml and also specify the android:style attribute like :
<com.mypack.MyView
style="#styles/MyCustomStyle"
...
/>
the 2nd constructor will also be called and default the style to MyCustomStyle before applying explicit XML attributes.
The third constructor is usually used when you want all of the Views in your application to have the same style.
If you override all three constructors, please DO NOT CASCADE this(...) CALLS. You should instead be doing this:
public MyView(Context context) {
super(context);
init(context, null, 0);
}
public MyView(Context context, AttributeSet attrs) {
super(context,attrs);
init(context, attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
// do additional work
}
The reason is that the parent class might include default attributes in its own constructors that you might be accidentally overriding. For example, this is the constructor for TextView:
public TextView(Context context) {
this(context, null);
}
public TextView(Context context, #Nullable AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
public TextView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
If you did not call super(context), you would not have properly set R.attr.textViewStyle as the style attr.
MyView(Context context)
Used when instanciating Views programmatically.
MyView(Context context, AttributeSet attrs)
Used by the LayoutInflater to apply xml attributes. If one of this attribute is named style, attributes will be looked up the the style before looking for explicit values in the layout xml file.
MyView(Context context, AttributeSet attrs, int defStyleAttr)
Suppose you want to apply a default style to all widgets without having to specify style in each layout file. For an example make all checkboxes pink by default. You can do this with defStyleAttr and the framework will lookup the default style in your theme.
Note that defStyleAttr was incorrectly named defStyle some time ago and there is some discussion about whether this constructor is really needed or not. See https://code.google.com/p/android/issues/detail?id=12683
MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
The 3rd constructor works well if you have control over the base theme of the applications. That is working for google because they ship their widgets along side the default Themes. But suppose you're writing a widget library and you want a default style to be set without your users needing to tweak their theme. You can now do this using defStyleRes by setting it to the default value in the 2 first constructors:
public MyView(Context context) {
super(context, null, 0, R.style.MyViewStyle);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs, 0, R.style.MyViewStyle);
init();
}
All in all
If you're implementing your own views, only the 2 first constructors should be needed and can be called by the framework.
If you want your Views to be extensible, you might implement the 4th constructor for children of your class to be able to use global styling.
I don't see a real use case for the 3rd constructor. Maybe a shortcut if you don't provide a default style for your widget but still want your users to be able to do so. Shouldn't happen that much.
Kotlin seems to take away a lot of this pain:
class MyView
#JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
: View(context, attrs, defStyle)
#JvmOverloads will generate all required constructors (see that annotation's documentation), each of which presumably calls super(). Then, simply replace your initialization method with a Kotlin init {} block. Boilerplate code gone!
The third constructor is much more complicated.Let me hold an example.
Support-v7 SwitchCompact package supports thumbTint and trackTint attribute since 24 version while 23 version does not support them.Now you want to support them in 23 version and how will you do to achieve this?
We assume to use custom View SupportedSwitchCompact extends SwitchCompact.
public SupportedSwitchCompat(Context context) {
this(context, null);
}
public SupportedSwitchCompat(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SupportedSwitchCompat(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mThumbDrawable = getThumbDrawable();
mTrackDrawable = getTrackDrawable();
applyTint();
}
It's a traditional code style.Note we pass 0 to the third param here. When you run the code, you will find getThumbDrawable() always return null how strange it is because the method getThumbDrawable() is its super class SwitchCompact's method.
If you pass R.attr.switchStyle to the third param, everything goes well.So why?
The third param is a simple attribute. The attribute points to a style resource.In above case, the system will find switchStyle attribute in current theme fortunately system finds it.
In frameworks/base/core/res/res/values/themes.xml, you will see:
<style name="Theme">
<item name="switchStyle">#style/Widget.CompoundButton.Switch</item>
</style>
If you have to include three constructors like the one under discussion now, you could do this too.
public MyView(Context context) {
this(context,null,0);
}
public MyView(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
doAdditionalConstructorWork();
}
I created a custom slider that was working fine, but suddenly it started showing visual issues and i have no idea where to look to solve this problem.
the issue is the appearance of black borders/gradients around it. i tested on android 6 and android 4.0.3 as well. both are showing the same problem. on android 4.0.3, i can also see this problem around the actions in the toolbar when i press on them, it makes like a black gradient shadow.
any idea?
the code of my slider is:
public class StyledSeekBar extends SeekBar {
public StyledSeekBar(Context context) {
super(context);
this.init();
}
public StyledSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
this.init();
}
public StyledSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public StyledSeekBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
this.init();
}
/**
* Initializes the instance of this class.
*/
private void init(){
setThumb(getResources().getDrawable(R.drawable.apptheme_scrubber_control_selector_holo_light));
setIndeterminateDrawable(getResources().getDrawable(R.drawable.apptheme_scrubber_progress_horizontal_holo_light));
setProgressDrawable(getResources().getDrawable(R.drawable.apptheme_scrubber_progress_horizontal_holo_light));
}
}
it's no shadow. Looks like .png stretched. Try 9png
I found the solution! To fix this kind of issue, it is necessary to verify the 9-patch images and resolve all the bad patches. This can be done by using the draw9patch tool.
I'm having trouble understanding why my extended layout isn't working. I made a class which goes
public class MyLayout extends RelativeLayout {
public MyLayout(Context context) {
super(context);
}
}
I wrote the XML as
<package.MyLayout
. . .
</package.MyLayout>
The method where I get the error is in the activity where I have called setContentView(R.layout.layout_relative).
I don't understand what I'm doing wrong because surely you inflate in the activity from the XML layout which is building on the custom class where I can make my overrides?
you need the other constructor, the one that takes two parameters:
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
which is used when the layout is inflated from the layout
You have specified the wrong constructors!
Android xml inflation uses
public RelativeLayout (Context context, AttributeSet attrs, int
defStyleAttr)
public RelativeLayout (Context context, AttributeSet
attrs, int defStyleAttr, int defStyleRes) since api 21
Is it possible to open a SlidingDrawer when viewed inside the Eclipse graphical layout preview? By default it's closed when viewed so I cannot see what is happening with the layouts inside the SlidingDrawer.
If this isn't possible, what would be the best way to handle this problem? A separate layout file I guess?
I am not sure if there is a standard way to do this.
I currently use the following method: override SlidingDrawer.onFinishInflate() to force it open when in Eclipse layout preview.
import android.widget.SlidingDrawer;
public class MySlidingDrawer extends SlidingDrawer {
public MySlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MySlidingDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
if (isInEditMode()) {
open();
}
}
}
Then, of course, replace SlidingDrawer by my.package.MySlidingDrawer in layout.xml.
I have simply extended the ImageView so an image goes full width. Like so:..
public class BannerImageView extends ImageView {
public BannerImageView(Context context) {
super(context);
}
public BannerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BannerImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
In XML I have declared it as follows:
<com.whatever.next.BannerImageView
android:id="#+id/banner"
android:src="#+drawable/logo"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
I receive the following errors:
main.xml: Unable to resolve drawable "com.android.layoutlib.bridge.ResourceValue#48537a0f" in attribute "src"
then I get the expected null pointer exceptions.
I am confused as I thought since I am not altering the default behaviour of the ImageView it would show in the graphical layout. I have read through the other similar questions and that confused me some more.
For the record the above code works fine on an actual device.
Any help is appreciated!
instead of
android:src="#+drawable/logo"
use
android:src="#drawable/logo"
No + for the src attribute