Search code examples
c#androidxamarin.androidforeground

Setting the foreground resource programmatically


I have created a LinearLayout like this:

<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">

Now I want to change the foreground resource programmatically, but I don't know how. I can change the background resource like this:

LayoutProfit.SetBackgroundResource(Resource.Drawable.list_divider_top_sides);

I want to change the color and the border of the layout, but that's not working if I use both the background, because it is a border OR a color then...

So how can I change the Foreground resource?


Solution

  • If you want to set the layout's foreground color you can use:

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

    But if you want to set a border on this layout, you have to define a shape in Resources/drawable/border.xml as:

    <?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>
    

    Then utilize it on your layout like:

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