繁体   English   中英

ListView自定义适配器上的SetBackgroundResource出现错误

[英]SetBackgroundResource on listview custom adapter getting error

我正在尝试在适配器内创建自定义listview行颜色

这是我的xml

artist_list_backgroundcolor

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
 <item 
 android:state_selected="false"
    android:state_pressed="false" 
    android:color="#6495ED" />
<item android:state_pressed="true" 
   android:color="#ffffff" />
<item android:state_selected="true"
 android:state_pressed="false" 
     android:color="#E5F5FA" />
</selector> 

这是我的适配器内的代码

public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(mContext).Inflate(Resource.Layout.CategoryPreview, null, false);

        }

        TextView txtCategoryName = row.FindViewById<TextView>(Resource.Id.txtCategoryName);
        txtCategoryName.Text = mitems[position].CategoryName;
        TextView txtCategoryID = row.FindViewById<TextView>(Resource.Id.txtCategoryID);
        txtCategoryID.Text = mitems[position].CategoryID;

        row.SetBackgroundResource(Resource.Drawable.artists_list_backgroundcolor);

        return row;
    }

当活动开始时,我遇到了错误

Android.Content.Res.Resources + NotFoundException:Drawable WiOrderAndroid.WiOrderAndroid:drawable / artists_list_backgroundcolor资源ID为#0x7f020053

仅当我将以这种方式设置xml时,它才起作用。

    <?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" >
    <shape>
      <solid
          android:color="#ef4444" />

    </shape>
  </item>

</selector>

但这是正确的方法吗?

尝试改用R.drawable.artists_list_backgroundcolor

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
  <item 
 android:state_selected="false"
    android:state_pressed="false" 
    android:color="#6495ED" />
<item android:state_pressed="true" 
   android:color="#ffffff" />
<item android:state_selected="true"
 android:state_pressed="false" 
     android:color="#E5F5FA" />
</selector> 

从以上代码中,您定义的是ColorStateList ,它应该位于res/color/artists_list_backgroundcolor.xml路径中,而不是res/drawable/ ,并且应该由@color/artists_list_backgroundcolorResource.Color.artists_list_backgroundcolor @color/artists_list_backgroundcolor

您需要一个drawable selector 请参考这里

更新:

SetBackgroundResource方法:

将背景设置为给定的资源。 资源应引用Drawable对象或0以删除背景。

资源应位于drawable文件夹中,但artists_list_backgroundcolor文件属于ColorStateList ,它应位于/res/color/文件夹中,而不是drawable文件夹中。

如果要使用artists_list_backgroundcolor文件,则需要将其放在/res/color/文件夹中。 但是您不能按row.SetBackgroundResource(Resource.Drawable.artists_list_backgroundcolor);使用它row.SetBackgroundResource(Resource.Drawable.artists_list_backgroundcolor); ,请参考此内容以使用ColorStateList

暂无
暂无

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

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