简体   繁体   English

设置前景以编程方式查看

[英]Set foreground to view programmatically

I already programmatically setting background.Now I have to add a ripple effect to my LinearLayout, so I need to set not only background, but also foreground我已经以编程方式设置背景。现在我必须为我的 LinearLayout 添加涟漪效果,所以我不仅需要设置背景,还需要设置前景

Code:代码:

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

You could get the drawable from that attribute resource as followed:您可以从该属性资源中获取 drawable,如下所示:

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

Which you would then use as followed:然后您将使用如下:

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

if you have the foreground ripple xml:如果你有前景涟漪xml:

for example ripple_foreground.xml (in Resources/drawable-v21 ):例如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>

you could set like this:你可以这样设置:

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

and need to set the LinearLayout property并且需要设置 LinearLayout 属性

android:clickable="true"

the effect like this:效果是这样的:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM