答案 0 :(得分:0)
您无法转换对象,因为它是不同的类型,例如,请使用以下代码:
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]
但是从https://developer.android.com/reference/android/view/View.html判断: 并且:https://developer.android.com/reference/android/widget/RelativeLayout.html
RelativeLayout是View的子类。 android.support.constraint.Constraintlayout是View
的子类but a android.support.constraint.Constraintlayout can't be cast to a RelativeLayout
你基本上要做的是
RelativeLayout relativeLayout = (RelativeLayout) constraintLayout;
其中RelativeLayout不是constraintLayout的超类。
答案 1 :(得分:0)
在xml文件中检查您的relativelayout
的ID。似乎ID rootlayout
属于constraint layout
。在xml文件中更改相对布局的id。
或将您的rootlayout
声明改为
ContraintLayout rootlayout = (ConstraintLayout) findViewById(R.id.rootlayout);