首页 > 解决方案 > 设置前景以编程方式查看

问题描述

我已经以编程方式设置背景。现在我必须在我的 LinearLayout 中添加波纹效果,所以我不仅需要设置背景,还需要设置前景

代码:

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var vh = holder as StaffViewHolder;

            vh.Layout.SetBackgroundColor(position % 2 == 0 ? Color.ParseColor("#ffffff") : Color.ParseColor("#f5f5f5"));
            //vh.Layout.Foreground = "?attr/selectableItemBackground";
            vh.StaffTv.Text = items[position].Name;
        }

        class StaffViewHolder : RecyclerView.ViewHolder
        {
            public TextView StaffTv { get; private set; }
            public LinearLayout Layout { get; private set; }

        public StaffViewHolder(View view) : base(view)
        {
            StaffTv = view.FindViewById<TextView>(Resource.Id.StaffItemLayout_textTv);
            Layout = view.FindViewById<LinearLayout>(Resource.Id.StaffItemLayout_layout);
        }
    }

标签: c#xamarin.android

解决方案


您可以从该属性资源中获取可绘制对象,如下所示:

public Drawable GetDrawableFromAttrRes(int attrRes, Context context)
{
    TypedArray a = context.ObtainStyledAttributes(new int[] { attrRes });
    try
    {
        return a.GetDrawable(0);
    }
    finally
    {
        a.Recycle();
    }
}

然后您将按如下方式使用:

vh.Layout.Foreground = GetDrawableFromAttrRes(Resource.Attribute.selectableItemBackground, context);

推荐阅读