Xamarin Android SetBackgroundDrawable 已弃用但 SetBackground() 未弃用

Xamarin Android SetBackgroundDrawable deprecated but not SetBackground()

var textView = parentView.FindViewById<TextView>(Resource.Id.txt_chat_message);
GradientDrawable gd = new GradientDrawable();
gd.SetCornerRadius(10);
gd.SetColor(Color.Yellow);
textView.SetBackgroundDrawable(gd);

如上例所示,SetBackgroundDrawable 允许我以编程方式控制颜色和半径。我看过 SetBackgroundResouce 但我找不到一个明确的例子,因为它似乎只是将 ID 带到我无法以编程方式更改的资源。

有人可以帮我提供一个替代方案,让我可以灵活地执行与上述 SetBackgroundDrawable 完全相同的操作吗?

使用Background属性。通常,每当 Android 具有不带参数的 getX/setX 方法时,Xamarin 会将其转换为名为 X.

的 C# 样式 属性
var textView = parentView.FindViewById<TextView>(Resource.Id.txt_chat_message);
GradientDrawable gd = new GradientDrawable();
gd.SetCornerRadius(10);
gd.SetColor(Color.Yellow);
textView.Background = gd;

编辑

基于 运行 它在设备上似乎 Background 属性 目前尚未完全实现 (11.11.2015)。我的试错方法指出,通过 属性 设置 Background 会抛出异常,因为它没有找到具有适当参数的 setBackground 方法。所以问题不在于获取可绘制对象的新方法,而是当您尝试设置它们时。也许我滥用了这个所以我愿意更正。

//Works
yesButton.SetBackgroundDrawable(ContextCompat.GetDrawable(context, Resource.Drawable.selector_green_button));

//Works
yesButton.SetBackgroundDrawable(ResourcesCompat.GetDrawable(Resources, Resource.Drawable.selector_green_button, Resources.NewTheme()));

//Doesn't Work     
yesButton.Background = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.selector_green_button, Resources.NewTheme());

//Doesn't Work
yesButton.Background = ContextCompat.GetDrawable(context, Resource.Drawable.selector_green_button);

//Doesn't Work
yesButton.Background = Resources.GetDrawable(Resource.Drawable.selector_green_button);

原答案

您可以使用背景 属性 正如@Jason 已经建议的那样。

为了使用它,您现在需要获取 Drawable 有趣的部分:

GetDrawable 方法已弃用(因为我认为 API 22)所以你应该使用 :

someControl.Background = ContextCompat.GetDrawable(context, Resource.Drawable.your_drawable);

而不是Resources.GetDrawable(Resource.Drawable.your_drawable);

找到这个 link 以供参考:

而不是 SetBackgroundDrawable(back); 使用 Background = back;

你必须这样做:

back = context.GetDrawable(Resource.Drawable.cover);
// SetBackgroundDrawable(back);
Background = back;`