[英]Set foreground to view programmatically
我已经以编程方式设置背景。现在我必须为我的 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);
}
}
您可以从该属性资源中获取 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);
如果你有前景涟漪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"
效果是这样的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.