简体   繁体   English

不幸的是,如果我将PaintDrawable强制转换为Drawable,则在调试时应用程序已停止

[英]unfortunately the app has stopped when i am debugging if I cast PaintDrawable to Drawable

I'm studying and trying to make some Android application with android studio. 我正在研究并尝试使用android studio制作一些Android应用程序。 But I found something that I can't understand. 但是我发现了我无法理解的东西。

If I write the sentence below, there is no problem: 如果我写下面的句子,那没有问题:

TextView vm = new TextView(this); TextView vm =新的TextView(this);

Drawable pnt = vm.getBackground(); Drawable pnt = vm.getBackground();

but, if I write a sentence like below, where I cast PaintDrawable to the righthand, and build this app and install apk to my device, app doesn't work showing message "Unfortunately, the app has stopped". 但是,如果我写如下句子,将PaintDrawable到右侧,然后构建该应用程序并将apk安装到我的设备上,则该应用程序将无法工作,并显示消息“不幸的是,该应用程序已停止”。

TextView vm = new TextView(this); TextView vm =新的TextView(this);

PaintDrawable pnt = (PaintDrawable) vm.getBackground(); PaintDrawable pnt =(PaintDrawable)vm.getBackground();

TextView::getBackground returns a Drawable , not necessarily a PaintDrawable. TextView :: getBackground 返回Drawable ,不一定是PaintDrawable。

You are attempting to downcast to PaintDrawable without checking whether you can do so. 您试图向下转换到PaintDrawable,而不检查是否可以这样做。 Try this: 尝试这个:

TextView vm = new TextView(this);

if (vm.getBackground() instanceof PainDrawable) {
    PaintDrawable pnt = (PaintDrawable) vm.getBackground();
    // ...
}
else {
    Log.d("SomeTag", vm.getBackground().getClass());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不幸的是,应用程序在调试时已停止 - Unfortunately app has stopped while debugging 不幸, <your app> 已停止,而我正在尝试在我的android模拟器中运行它。 如何解决呢? - unfortunately, <your app> has stopped while i am trying it run it in my android emulator. how to solve this? 不幸的是,应用程序已停止,我该如何解决? - unfortunately app has stopped,how can i solve it? 当我使用Genymotion模拟器运行我的第一个android应用程序时,不幸的是,其给出的错误“应用程序名称”已停止。 请帮我 - When I am running my first android app using Genymotion emulator its giving error unfortunately “app name” has stopped. Please help me 我如何解决这个问题(不幸的是应用程序已停止) - how I resolve this problem ( unfortunately App has stopped) 当我试图在我的设备上测试游戏时,“不幸的是,应用名称已停止 - when I tried to test the game on my device crushed "Unfortunately App name has stopped 不幸的是,当我想更新ListView时已经停止 - unfortunately has stopped when I want to update ListView 不幸的是,当我要推送片段时,Android已停止 - Android unfortunately has stopped when I want to push fragment 不幸的是应用程序已停止 - unfortunately app has stopped 不幸的是,使用ImageView时应用已停止 - unfortunately app has stopped when using ImageView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM