简体   繁体   English

Android - 无法扩展ImageView

[英]Android - Unable to extend ImageView

I simply want to extend ImageView: 我只是想扩展ImageView:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class SquareImageView extends ImageView {

    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        setMeasuredDimension(width, width);
    }

}

But Android Studio returns the compile error: 但是Android Studio会返回编译错误:

This custom view should extend android.support.v7.widget.AppCompatImageView instead 此自定义视图应该扩展android.support.v7.widget.AppCompatImageView

But importing android.support.v7.widget.AppCompatImageView insted of android.widget.ImageView does not solve the problem because ImageView is marked then as not imported... 但导入android.support.v7.widget.AppCompatImageViewandroid.widget.ImageView并没有解决问题,因为ImageView被标记为未导入...

What am I doing wrong here? 我在这做错了什么?

This works perfectly fine 这完全没问题

import android.content.Context;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

public class CustomImageView extends AppCompatImageView {
    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

When you import AppCompatImageView then you have to use it too. 导入AppCompatImageView您也必须使用它。 Not only this, in JAVA, what you import is what you use.putting it other way, you import what you want to use 不仅如此,在JAVA中, 您导入的内容就是您使用的内容。以其他方式输入,导入您想要使用的内容

Using AppCompat widgets allows you to have some features on devices with pre-Lollipop versions of Android. 使用AppCompat小部件,您可以在具有Android前Lollipop版本的设备上使用某些功能。

Use AppCompatImageView , ImageView will be fine now. 使用AppCompatImageViewImageView现在就可以了。

For those looking for an answer and are using the androidx libraries, here's an update. 对于那些寻找答案并正在使用androidx库的人来说,这是一个更新。

Yes, you still need to use AppCompatImageView , but just use the new libraries. 是的,您仍然需要使用AppCompatImageView ,但只需使用新库。 Here's the new import statement: 这是新的import语句:

import androidx.appcompat.widget.AppCompatImageView;

Just changing this import to this other answer should do the trick. 只需将此导入更改为其他答案即可

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM