在Android中扩展EditText.我究竟做错了什么?

tar*_*lex 13 java android extend android-custom-view android-edittext

所以我试图掌握在Android中使用自定义控件.但我的应用程序在尝试创建活动时崩溃了.这是代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是布局xml:

<com.myApp.MyEditText
     android:id="@+id/edtTaskName"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"/> 
Run Code Online (Sandbox Code Playgroud)

Fer*_*ego 17

您将需要实现这些构造函数:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,尝试执行以下操作:

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

您将在logcat中获得以下内容:

attribute name at index 0 = id 
Run Code Online (Sandbox Code Playgroud)

因此,要将这些XML属性提供给Super类(EditText),您必须覆盖这些构造函数.

希望有助于.

  • 谢谢!我希望我至少可以从编译器或运行时获得有关错误的信息.但Eclipse只是停在一些内部方法调用的中间,没有任何异常信息,没有错误,没有. (2认同)