程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> java-Android自定義view,空指針異常求解決

java-Android自定義view,空指針異常求解決

編輯:編程綜合問答
Android自定義view,空指針異常求解決
package com.drawview.drawview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linearlayout);
        LinearLayout l = (LinearLayout)findViewById(R.layout.linearlayout);
        DrawView dv = new DrawView(this);
        dv.setMinimumHeight(300);
        dv.setMinimumWidth(300);
        l.addView(dv);
    }
}

package com.drawview.drawview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class DrawView extends View{
    private float currentX = 30;
    private float currentY = 30;
    Paint p = new Paint();
    public DrawView(Context context) {
        super(context);
    }

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentX = event.getX();
        currentY = event.getY();
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        p.setColor(Color.MAGENTA);
        canvas.drawCircle(currentX,currentY,15,p);
    }
}

【錯誤提示】
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
at com.drawview.drawview.MainActivity.onCreate(MainActivity.java:17)
我知道錯誤的意思,也知道發生在哪兒,就是不知道怎麼解決。

最佳回答:


LinearLayout l = (LinearLayout)findViewById(R.layout.linearlayout);這段代碼不對,雖然R.layout.linearlayout也是int型,但不是控件,findViewById是找控件的。可以這麼解決,把這段代碼改成 LinearLayout l = (LinearLayout)findViewById(R.id.lin);,然後在你的布局文件中添加一個LinearLayout的控件:
android:id="@+id/lin"
android:layout_height="match_parent"
android:layout_width="match_parent">

</LinearLayout>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved