[英]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.