设置前景以编程方式查看

时间:2019-07-04 16:39:09

标签: c# xamarin.android

我已经以编程方式设置了背景。现在我必须在我的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);
        }
    }

2 个答案:

答案 0 :(得分:1)

您可以按照以下步骤从该属性资源中获取drawable:

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);

答案 1 :(得分:1)

如果您有前景涟漪图xml:

例如 ripple_foreground.xml (在 Resources / drawable-v21 中):

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
     android:color="#f5f5f5">
</ripple>

您可以这样设置:

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 = vh.ItemView.Context.GetDrawable(Resource.Drawable.ripple_foreground);
        vh.StaffTv.Text = items[position].Name;
    }

,并且需要设置LinearLayout属性

android:clickable="true"

这样的效果

enter image description here