【问题标题】:Change color of a drawable from code (xamarin.android)从代码更改可绘制对象的颜色 (xamarin.android)
【发布时间】:2018-11-20 22:14:59
【问题描述】:

我已经获得了一些代码来扩展一个 android 应用程序。

主要活动有一个展示按钮的 FrameLayout。按钮的背景是可绘制的 (XML)。

==> 资源/布局/Layout.axml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#999999">
    .../...
     <Button
            android:id="@+id/the_button"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center_horizontal|bottom"
            android:layout_marginBottom="40dp"
            android:gravity="center_vertical|center_horizontal"
            android:background="@drawable/btn" />
    </FrameLayout>

按钮使用可绘制对象使其看起来带有边框。

==> 资源/drawable/btn.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="false">
    <shape android:shape="oval">
      <solid android:color="#20000000"/>
      <stroke android:width="2dp" android:color="#000000"/>
      <size android:width="60dp" android:height="50dp" />
    </shape>
  </item>
  <item android:state_pressed="true">
    <shape android:shape="oval">
      <solid android:color="#FF000000"/>
      <stroke android:width="2dp" android:color="#000000"/>
      <size android:width="60dp" android:height="50dp" />
    </shape>
  </item>
</selector>

在应用程序的生命周期中,按钮的边框(上图)应该会改变颜色。如何更改上面笔划的颜色? 使用通常的FindViewById&lt;Button&gt;(Resource.Id.the_button) 没有帮助。

提前致谢。

解决方案 - 感谢 G.hakim

Button _theButton = FindViewById<Button>(Resource.Id.the_button);
GradientDrawable _stroke = (GradientDrawable)_theButton.Background.Current;
_stroke.SetStroke(2, Color.Red);

【问题讨论】:

  • 你可以试试this var bgShape = (GradientDrawable)holder.BtnAttend.Background.Current; bgShape.SetColor(Color.ParseColor("#29AE53"));

标签: android xamarin xamarin.android


【解决方案1】:

我会这样做:

var button= FindViewById<Button>(Resource.Id.the_button);
var gradientDrawable = button.Background.Current as GradientDrawable;
gradientDrawable.SetColor(your_color);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多