Extending a EditText in Android. What am I doing wrong?

后端 未结 3 1590
无人及你
无人及你 2021-01-04 06:43

So I\'m trying to get a grasp of using custom controls in Android. But my app crashes on trying to create the activity. Here\'s the code:

package com.myApp;
         


        
3条回答
  •  离开以前
    2021-01-04 07:07

    You will need to implement these constructors:

    public class TestEditText extends EditText {
        public TestEditText(Context context) {
            super(context);
        }
    
        public TestEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public TestEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public TestEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    }
    

    for example try to do the following :

    public TestEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.i("attribute name at index 0", attrs.getAttributeName(0));
    }
    

    you will get the following in your logcat :

    attribute name at index 0 = id 
    

    so to deliver these XML attributes to the Super class (EditText) you have to override these constructors.

    Hope that Helps.

提交回复
热议问题