安卓 - imageView.getDrawable() 返回 null

4
我卡在了这个看似简单的问题上。我做错了什么?
ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView)findViewById(R.id.control);
        ClipDrawable drawable = (ClipDrawable)mImageView.getDrawable();
        drawable.setLevel(10);

    }

应用程序在drawable.setLevel(10)处崩溃,并显示NullPointerException(drawable为空)。

这是我的xml:

circle.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:innerRadius="50dp"
    >

    <solid
        android:color="#FFAAFF"/>

</shape>

clip.xml

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:clipOrientation="horizontal"
    android:drawable="@drawable/circle"
    android:gravity="clip_horizontal"

/>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ImageView
        android:id="@+id/image"
        android:layout_height="100dp"
        android:layout_width="100dp"
        android:background="@drawable/clip"
        android:layout_centerHorizontal="true"
        />

</RelativeLayout>

请在这里帮助我!(涉及IT技术)
1个回答

16

您将可绘制对象设置为“src”的background属性。

android:background="@drawable/clip"

因此,请通过将background属性替换为src来更改您的activity_main.xml

android:src="@drawable/clip"

最后,您的activity_main.xml将是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ImageView
    android:id="@+id/image"
    android:layout_height="100dp"
    android:layout_width="100dp"
    android:scr="@drawable/clip"
    android:layout_centerHorizontal="true"
    />

或者您可以调用方法getBackground()获取可绘制对象,该对象是由属性android:background设置的可绘制对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接