以编程方式更改XML背景-Xamarin.Android C#

问题描述

我正在尝试使用background C#以编程方式更改Button Xamarin.Android属性,但无法完成。

Xml文件

... <Button
                        p1:id="@+id/BtnGo"
                        p1:layout_width="wrap_content"
                        p1:layout_height="30dp"
                        p1:paddingHorizontal="15dp"
                        p1:text="Go"
                        p1:textColor="#ffffff"
                        p1:textSize="15dp"
                        p1:background="@drawable/togglefocus"
                        p1:textAllCaps="false"
                        p1:layout_gravity="center" /> ...

需要改变

p1:background="@drawable/togglefocus"

收件人

p1:background="@drawable/myfocus"

但是要在执行时/以编程方式(C#)。

试过这个:

        Btn = FindViewById<Button>(Resource.Id.BtnGo);
        Btn.Click += delegate           
        {                
            Btn.Background("@drawable/myfocus"); //myfocus is an xml file in: Resources > Drawable
        };

有什么想法吗?

解决方法

如果我没记错,可以为此使用SetBackgroundResouce方法:

  Btn = FindViewById<Button>(Resource.Id.BtnGo);
    Btn.Click += delegate           
    {   
       Btn.SetBackgroundResource(Resource.Drawable.myfocus);
    };

祝你好运! 如有疑问,请随时回来!