Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
import android.content.Context;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnClickListener;

public class MyEditText extends EditText implements OnClickListener {

    public MyEditText(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }   
    public void FlashBorder()
    {
        //do some custom action
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        EditText txt = (EditText) v;
        txt.selectAll();
    }
}

Here's the layout xml:

<com.myApp.MyEditText
     android:id="@+id/edtTaskName"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"/> 
like image 672
taralex Avatar asked Oct 04 '11 13:10

taralex


2 Answers

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.

like image 191
Fernando Gallego Avatar answered Sep 21 '22 13:09

Fernando Gallego


You have to add this constructor for creating any custom View.

public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
.....
}

instead of

public MyEditText(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }  
like image 44
Lalit Poptani Avatar answered Sep 20 '22 13:09

Lalit Poptani