C# - Resources.GetDrawable在Android Xamarin中已经过时了

Jak*_*ler 6 c# android android-layout xamarin.android xamarin

Resources.GetDrawable在andrdoid Xamarin中实现了.该程序有效,但如果我点击按钮实现Resources.GetDrawable程序强制关闭.这是我的代码:

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));
Run Code Online (Sandbox Code Playgroud)

Resources.GetDrawable(Resource.Drawable.paint_pressed得到绿色下划线(在Visual Studio 2015年Xamarin).日志消息返回异常:

Android.Content.Res.Resources + NotFoundException

'Resources.GetDrawable(int)'已过时:'deprecated'

对于Java版本,解决方案是使用以下三种方法之一:

ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
//or
ContextCompat.getDrawable(getActivity(), R.drawable.name);
//or
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
Run Code Online (Sandbox Code Playgroud)

C#Android Xamarin的版本是什么?谢谢.

Ruc*_*ira 6

var currPaint= ContextCompat.GetDrawable(this,Resource.Drawable.paint_pressed);
        currPaint.SetBounds(0, 0, 60, 60);
Run Code Online (Sandbox Code Playgroud)

这就是我在我的项目中所表达的,即使我有同样的问题.希望这有帮助!@Jake


Nic*_*ert 6

(对于Xamarin Forms项目)

当我需要从我的.Droid项目中获取 drawable 时,我通常使用以下行:

Control.Background = Context.GetDrawable(Resource.Drawable.ResourceName);
Run Code Online (Sandbox Code Playgroud)


M. *_*cki 5

改成SetImageResource这样

currPaint.SetImageResource(Resource.Drawable.paint_pressed);
Run Code Online (Sandbox Code Playgroud)