【问题标题】:What kind of LayoutParams should I use?我应该使用哪种 LayoutParams?
【发布时间】:2014-04-21 23:20:22
【问题描述】:

问题描述:

我有一个自定义的 ImageView:

public class TestImageView extends ImageView {
...
    public void onImageLoaded(Bitmap bitmap) {
        int width = DeviceInfo.getScreenWidth();
        int height = width * (float) bitmap.getHeight() / (float) bitmap.getWidth();
        ViewGroup.MarginLayoutParams layoutParams =
                new ViewGroup.MarginLayoutParams(width, height);
        this.setLayoutParams(layoutParams);
    }
}

然后我收到了这个错误:

java.lang.ClassCastException: android.view.ViewGroup$MarginLayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams

在我的项目中,我确实将 TestImageView 的一个实例作为 FrameLayout 的子级。因此,如果我将 ViewGroup.MarginLayoutParams 更改为 FrameLayout.LayoutParams 它将起作用。但是这个定制的 ImageView 可以在其他类型的布局中,比如 LinearLayout。我认为我不应该在这里将其限制为 FrameLayout.layoutParams。

那么我应该在这里做什么?更一般地说,为什么 Android 会制作不同的 LayoutParams? LayoutParams 类似乎相同?我认为没有必要。

【问题讨论】:

  • 你试过使用 LinearLayout.LayoutParams 吗?

标签: android android-layout


【解决方案1】:

ViewGroup 的每个子类都有自己的 LayoutParams(从 ViewGroup.MarginLayoutParams 下降,它是 ViewGroup.LayoutParams 的后代(每个子类没有 MarginLayoutParams,因为边距设置功能可以通过继承获得)),因为它们支持不同的素质。例如 LinearLayout.LayoutParams 支持使用重力。因此,根据您的 ImageView 所在的 ViewGroup 类型,您的 LayoutParams 必须是相同的类型,或者至少转换为相同的类型。你有几个选择。一种是假设在您由 ImageView 制作的子类中您将始终使用某种类型的布局,然后将 ViewGroup.MarginLayoutParams 替换为(您的布局类型).LayoutParams。但是如果你改变了它,它就会停止工作,所以你可以通过使用泛型来避免所有这些:

public class TestImageView<I extends ViewGroup.LayoutParams> extends ImageView {
    public void onImageLoaded(Bitmap bitmap) {
        int width = DeviceInfo.getScreenWidth();
        int height = width * (float) bitmap.getHeight() / (float) bitmap.getWidth();
        I layoutParams = (I)
                new ViewGroup.LayoutParams(width, height);
        this.setLayoutParams(layoutParams);
    }
}

及其用途:

// using a RelativeLayout
TestImageView<RelativeLayout.LayoutParams> iv = new TestImageView<>();

希望对您有所帮助! (虽然我目前没有我的测试设备,所以如果它不起作用,请发表评论)

【讨论】:

  • 这里不需要泛型,否则这是正确的。 ViewGroup.LayoutParams 是所有 LayoutParams 的基类。由于他不依赖边距,他可以简单地将 MarginLayoutParams 替换为 :ayou
【解决方案2】:

我浏览了 Android 框架中的一些源代码。我认为我做的不对:

布局应该是视图父级的工作!!

所以我不应该把代码放在 TestImageView 中。相反,它应该放在 View 的父级中:

public class ParentOfTestImageView extends LinearLayout {
...
...
...
    public void whateverFunction() {
        TestImageView imageView = new TestImageView(context);
        // Note here
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(whateverWidth, whateverHeight);
        imageView.setLayoutParams(params);
        imageView.requestLayout();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多