【问题标题】:how to fix this casting error for Relativelayout如何修复Relativelayout的这个转换错误
【发布时间】:2018-01-13 11:07:00
【问题描述】:

【问题讨论】:

标签: java android android-layout


【解决方案1】:

在 xml 文件中检查您的relativelayout id。似乎 id rootlayout 属于 constraint layout。更改 xml 文件中相同的相对布局的 id。

或将您的 rootlayout 声明更改为

ContraintLayout rootlayout = (ConstraintLayout) findViewById(R.id.rootlayout);

【讨论】:

  • 欢迎。很高兴提供帮助:)
【解决方案2】:

您不能转换对象,因为它是不同的类型,例如使用以下代码:

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 的超类。

【讨论】:

  • 非常感谢您,先生。您的解释对我很有帮助,我非常感谢您的努力。
  • 不客气,如果还有什么不明白的可以在下方评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
相关资源
最近更新 更多