为什么我在Drawable pic =(Drawable)获得NPE i.getDrawable(); ?????? 我试图获得drawable的高度和宽度,以便通过矩阵(使用矩阵启用多点触控)将其比例设置为适合图像切换器中的imageview的XY。
public View makeView() {
ImageView i = new ImageView(this);
Drawable pic = (Drawable) i.getDrawable();
float displayHeight = i.getHeight();
float imageHeight = pic.getIntrinsicHeight();
float displayWidth = i.getWidth();
float imageWidth = pic.getIntrinsicWidth();
float scaleX = (float) displayWidth / (float) imageWidth;
float scaleY = (float) displayHeight / (float) imageHeight;
matrix.setScale(scaleX, scaleY);
i.setBackgroundColor(0xFF000000);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
i.setImageMatrix(matrix);
i.setScaleType(ScaleType.MATRIX);
错误日志:
E/AndroidRuntime(22016): FATAL EXCEPTION: main
E/AndroidRuntime(22016): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ben.test/com.ben.test.ImageSwitch1}: java.lang.NullPointerException
E/AndroidRuntime(22016): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
E/AndroidRuntime(22016): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime(22016): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E /AndroidRuntime(22016): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime(22016): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(22016): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(22016): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(22016): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(22016): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(22016): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
E/AndroidRuntime(22016): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
E/AndroidRuntime(22016): at dalvik.system.NativeStart.main(Native Method)
E /AndroidRuntime(22016): Caused by: java.lang.NullPointerException
E/AndroidRuntime(22016): at com.ben.test.ImageSwitch1.makeView(ImageSwitch1.java:185)
E/AndroidRuntime(22016): at android.widget.ViewSwitcher.obtainView(ViewSwitcher.java:80)
E/AndroidRuntime(22016): at android.widget.ViewSwitcher.setFactory(ViewSwitcher.java:99)
E/AndroidRuntime(22016): at com.ben.test.ImageSwitch1.onCreate(ImageSwitch1.java:100)
E/AndroidRuntime(22016): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(22016): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime(22016): ... 11 more
W/ActivityManager( 1106): Force finishing activity com.ben.test/.ImageSwitch1
W/ActivityManager( 1106): Force finishing activity com.ben.test/.LP
答案 0 :(得分:1)
getDrawable()几乎肯定会返回一个空值。这本身不是问题,但是当你尝试将该空值转换为Drawable时,你得到一个NPE。
潜在的问题是新创建的ImageView还没有与之关联的drawable(正如它返回null所证明的那样)