Java 如何修复Relativelayout的此强制转换错误
Java 如何修复Relativelayout的此强制转换错误,java,android,android-layout,Java,Android,Android Layout,无法强制转换对象,因为它是另一种类型,例如,以下代码: public class Fruit { protected int size; public Fruit(int size) { this.size = size; } } public class Banana extends Fruit { private Color color; public Banana(int size, Color color) {
无法强制转换对象,因为它是另一种类型,例如,以下代码:
public class Fruit {
protected int size;
public Fruit(int size) {
this.size = size;
}
}
public class Banana extends Fruit {
private Color color;
public Banana(int size, Color color) {
super(size);
this.color = color;
}
}
public class Main {
public static void main(String[] args) {
Fruit someFruit = new Fruit(5);
Banana yellowNanner = new Banana(3, Color.YELLOW);
Fruit greenBanana = new Banana(4, Color.GREEN);
// Allowed cast because Banana is a fruit (extends it, no need to explicitly cast) [1]
Fruit generalBanana = yellowNanner;
// Allowed cast because The fruit was a banana originally [2]
Banana stillABanana = (Banana) greenBanana;
// Disallowed cast because Fruit isn't necessarily a banana [3]
Banana notABanana = (Banana) someFruit; // gives a runtime exception (ClassCastException)
// Disallowed cast, String isn't related to fruit [4]
Fruit definitelynotfruit = (Fruit) "Pretend to be fruit"; // gives a runtime exception, and probably a compiler one too
}
}
我想说的是,你在铸造一些无法铸造的东西。检查您试图强制转换到的对象是否是一个超类或与它来自的类相同的级别
您正在经历的案例可能是[3]或[4]
但从以下几点来看:
以及:
RelativeLayout是视图中的一个子类。
android.support.constraint.Constraintlayout是视图中的一个子类
but a android.support.constraint.Constraintlayout can't be cast to a RelativeLayout
你基本上想做的是
RelativeLayout relativeLayout = (RelativeLayout) constraintLayout;
其中RelativeLayout不是constraintLayout的超类。检查xml文件中的
RelativeLayout
的id。idrootlayout
似乎属于约束布局
。更改xml文件中相同相对布局的id
或者将您的rootlayout
declaration更改为
ContraintLayout rootlayout = (ConstraintLayout) findViewById(R.id.rootlayout);
在这里发布代码和错误的图片是不受欢迎的,因为这使我们更难帮助您解决问题。最好是直接将相关代码和/或错误复制粘贴到问题中。请阅读,然后回答您的问题。非常感谢,先生。你的解释对我帮助很大,我真的很感谢你的努力。欢迎你,如果你还有什么不明白的地方,请在下面评论。欢迎。很乐意帮忙:)