Android自定义视图问题

问题描述

| 嗨,大家好,我一直在与这个问题作斗争,不知道是什么原因。我有一个简单的布局如下
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<view xmlns:android=\"http://schemas.android.com/apk/res/android\" class=\"com.dinash.notepad.NotePade$LinedEditText\" />
活动类如下:
public class NotePade extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;
    // we need this constructor for LayoutInflater
    public LinedEditText(Context context,AttributeSet attrs) {
        super(context,attrs);
        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL_AND_stroke);
        // mPaint.setColor(R.color.edit_note_line); //SET YOUR OWN COLOR
        // HERE
        mPaint.setColor(Color.RED); // SET YOUR OWN COLOR HERE
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // int count = getLineCount();
        int height = getHeight();
        // int height = 100;
        int line_height = getLineHeight();
        int count = height / line_height;
        if (getLineCount() > count)
            count = getLineCount();// for long text with scrolling

        Rect r = mRect;
        Paint paint = mPaint;
        int baseline = getLineBounds(0,r);// first line
        for (int i = 0; i < count; i++) {
            canvas.drawLine(r.left,baseline + 1,r.right,paint);
            baseline += getLineHeight();// next line
        }
        super.onDraw(canvas);
    }
}
} 当我启动应用程序时,我不断收到此错误
05-26 11:31:21.604: ERROR/AndroidRuntime(1537): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class com.dinash.notepad.NotePade$LinedEditText
然后
05-26 11:31:21.604: ERROR/AndroidRuntime(1537): Caused by: java.lang.NoSuchMethodException: LinedEditText(Context,AttributeSet)
任何人都可以告诉我问题出在哪里... 提前致谢     

解决方法

您需要使内部类静态化。否则,它将始终需要NotePade实例来为其提供初始化上下文。 看这里。     ,将您的自定义视图移到单独的文件中。     ,我想在一个单独的类中编写您的自定义视图,并且您的布局应该像这样...
<com.dinash.notepad.LinedEditText></com.dinash.notepad.LinedEditText>