Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Resources.GetDrawable is obsolete in Android Xamarin

I implemented Resources.GetDrawable in andrdoid Xamarin. The program works, but if I clicked the button implementing the Resources.GetDrawable the program force close. Here's my code:

SetContentView(Resource.Layout.Main);
drawView = FindViewById<DrawingView>(Resource.Id.drawing);
LinearLayout paintLayout = FindViewById<LinearLayout>(Resource.Id.paint_colors);
currPaint = (ImageButton)paintLayout.GetChildAt(0);
currPaint.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.paint_pressed));

The Resources.GetDrawable(Resource.Drawable.paint_pressed got green underlined(Xamarin in Visual Studio 2015). The log message returned exception:

Android.Content.Res.Resources+NotFoundException

'Resources.GetDrawable(int)' is obsolete: 'deprecated'

For Java version the solution is by using one of these 3:

ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
//or
ContextCompat.getDrawable(getActivity(), R.drawable.name);
//or
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);

What is the version for C# Android Xamarin?, Thank you.

like image 927
Jake Muller Avatar asked Sep 17 '16 12:09

Jake Muller


Video Answer


2 Answers

var currPaint= ContextCompat.GetDrawable(this,Resource.Drawable.paint_pressed);
        currPaint.SetBounds(0, 0, 60, 60);

This is what i have implimented in my project even i had same problem.Hope this helps! @Jake

like image 143
Ruchira Avatar answered Sep 28 '22 07:09

Ruchira


Change to SetImageResource like this

currPaint.SetImageResource(Resource.Drawable.paint_pressed);
like image 41
M. Wiśnicki Avatar answered Sep 28 '22 07:09

M. Wiśnicki