java - Android自定义 View : getting null references on every class members in the onDraw method

标签 java android nullpointerexception android-view ondraw

我正在尝试创建一个 Android 自定义 View ,但我遇到了一个相当奇怪的问题。

我在构造函数中设置的每个数据成员(字符串、位图...)在重写的 onDraw 方法中都变为 null。

代码如下:

public class SimulationView extends View
{
private static final String TAG = "SIMULATION_VIEW";
private String str;
private Bitmap mField;

public SimulationView(Context context) {
    super(context);
    str = new String("hello"); 
    mField = BitmapFactory.decodeResource(getResources(), R.drawable.field);
    Log.i(TAG_DEBUG, mField.getHeight() + " " + mField.getWidth()); // displays "1518 900" properly
    Log.i(TAG, str); // displays "hello" properly
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.i(TAG, str); // throws java.lang.NullPointerException
    Log.i(TAG, mField.getHeight() + " " + mField.getWidth()); // throws java.lang.NullPointerException (when previous line is commented of course)
    invalidate();
}

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

public SimulationView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context);
}

private void init(Context context) {
}

这是当字符串导致NPE时的堆栈跟踪:

   Process: com.example.simulation_view, PID: 5207
java.lang.NullPointerException: println needs a message
        at android.util.Log.println_native(Native Method)
        at android.util.Log.i(Log.java:160)
        at com.example.simulation_view.SimulationView.onDraw(SimulationView.java:84)
        at android.view.View.draw(View.java:15114)

这是当位图导致 NPE 时的堆栈跟踪:

  java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getHeight()' on a null object reference
        at com.example.simulation_view.SimulationView.onDraw(SimulationView.java:83)
        at android.view.View.draw(View.java:15114)

我做错了什么? 任何帮助将不胜感激!

祝你有美好的一天

最佳答案

你的 init 方法是空的。仅当您以编程方式实例化自定义 View 时,您的代码才有效。如果在 xml 中声明,则 Bitmap 和 String 不会被初始化。使用init进行初始化,并在仅使用Context作为参数的构造函数中调用它

private void init(Context context) {
    str = "hello"; 
    mField = BitmapFactory.decodeResource(getResources(), R.drawable.field);
}

关于java - Android自定义 View : getting null references on every class members in the onDraw method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066128/

相关文章:

java - 我的程序给出了错误的输出

java - 为什么在 Java 中不可能在内部匿名类中引用非最终变量?

android - 预发布报告详细信息抛出稳定性问题 : android. apps.wellbeing

java - 我怎样才能同步类,以便我可以从 UI 线程和后台线程使用?

java - ExecutorService.Submit(Callable<T>) 正在为 Future<T> 对象返回空值

java - 线程 "main"java.lang.NullPointerException 中的异常 - Json 到 Java

java - 没有 Spring MVC 的 Spring Web 上下文

java - 无法运行 flutter doctor --android-licenses

java - 如何在android中将毫秒转换为日期格式?

java - 字符串数组中的空指针异常