以编程方式设置前台资源

Setting the foreground resource programmatically

我创建了一个这样的 LinearLayout:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:id="@+id/LayoutProfit"
    android:layout_width="0dp"
    android:layout_weight="20"
    android:layout_height="27dp"
    android:minWidth="0px"
    android:minHeight="50px"
    android:background="#edf0f4"
    android:foreground="@drawable/list_divider_full">

现在我想以编程方式更改前台资源,但我不知道如何。我可以这样更改背景资源:

LayoutProfit.SetBackgroundResource(Resource.Drawable.list_divider_top_sides);

我想更改布局的颜色和边框,但如果我同时使用背景,那将不起作用,因为它是边框或颜色...

那么如何更改前台资源呢?

如果您想设置布局的前景色,您可以使用:

var LayoutProfit = FindViewById<LinearLayout>(Resource.Id.LayoutProfit);
var drawable = new GradientDrawable();
drawable.SetColor(Resource.Color.colorAccent);
LayoutProfit.Foreground = drawable;

但是如果你想在这个布局上设置边框,你必须在Resources/drawable/border.xml中定义一个形状为:

<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <stroke android:width="5dip" android:color="@android:color/holo_red_dark" />
</shape>

然后在您的布局中使用它,例如:

var LayoutProfit = FindViewById<LinearLayout>(Resource.Id.LayoutProfit);
LayoutProfit.SetBackgroundResource(Resource.Drawable.border);