I am stuck on this seemingly easy issue. What am I doing wrong ?
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);
}
The app crashes at drawable.setLevel(10) with a NullPointerException (drawable is null).
Here is my 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>
Please help me out here !
You set the drawable to background
attribute of 'src'.
android:background="@drawable/clip"
. So change yours activity_main.xml
by replacing background
attribute to src
:
android:src="@drawable/clip"
Finally yours activity_main.xml
will be:
<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"
/>
Or you can get yours drawable by calling method getBackground()
which returns drawable that was set by attribute android:background
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With