简体   繁体   中英

Android - Unable to extend ImageView

I simply want to extend 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:

This custom view should extend android.support.v7.widget.AppCompatImageView instead

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...

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. Not only this, in JAVA, what you import is what you use.putting it other way, you import what you want to use

Using AppCompat widgets allows you to have some features on devices with pre-Lollipop versions of Android.

Use AppCompatImageView , ImageView will be fine now.

For those looking for an answer and are using the androidx libraries, here's an update.

Yes, you still need to use AppCompatImageView , but just use the new libraries. Here's the new import statement:

import androidx.appcompat.widget.AppCompatImageView;

Just changing this import to this other answer should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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