设置自定义列表Xamarin中所选列表视图项的背景色



我有一个自定义ListView和一个自定义ViewCell,用于iOS和android的Xamarin Forms项目。我创建了自定义listView,这样我的列表就可以替换颜色(这非常成功)。不幸的是,当我创建自定义ListView时,它停止高亮显示所选单元格,所以这就是我创建自定义ViewCells的原因。

我在机器人方面遇到了麻烦。当单元格被选中时,我可以更改颜色。但我不知道一旦选择了另一个单元格,如何将颜色改回原来的颜色。

这是我的CustomList类。。。

public class CustomList : ListView
{
public CustomList (){}
protected override void SetupContent(Cell content, int index)
{
base.SetupContent (content, index);
var currentCell = content as ViewCell; 
currentCell.View.BackgroundColor = index % 2 == 0 ? Color.FromRgb (235, 235, 235) : Color.FromRgb (255, 255, 255); 
}
}

非常直接,只是根据索引设置颜色。(也许我可以在这里添加一些其他内容来处理所选单元格?)

这是CustomCell类:

public class CustomCell : ViewCell
{
public const String isSelectedProperty = "IsSelected"; 
public CustomCell ()
{
}
}

以及在iOS渲染器中:

public class CustomCellRenderer : ViewCellRenderer
{
private UIView view; 

public CustomCellRenderer ()
{
}
public override UITableViewCell GetCell (Cell item, UITableViewCell reusableCell, UITableView tv)
{
var cell = base.GetCell (item, reusableCell, tv); 
if (view == null) {
view = new UIView (cell.SelectedBackgroundView.Bounds);
view.Layer.BackgroundColor = UIColor.FromRGB (128, 204,255).CGColor;  
}
cell.SelectedBackgroundView = view; 
return cell; 
}
}

和android渲染器:

public class CustomCellRenderer : ViewCellRenderer
{
public CustomCellRenderer ()
{
}
protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
{
var cell = base.GetCellCore (item, convertView, parent, context);
return cell;
}
protected override void OnCellPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnCellPropertyChanged (sender, e);
var customCell = sender as CustomCell; 
if (e.PropertyName == CustomCell.isSelectedProperty) {
customCell.View.BackgroundColor = Color.FromRgb (128, 204, 255); 
} 
}
}

所以iOS部分是有效的。机器人部分"工作",因为它选择了细胞的颜色,但颜色保持不变。我只希望选定的单元格具有不同的背景颜色。有什么想法吗?

对于Android,在自定义主题定义中的styles.xml中,我设置了:

<item name="android:colorFocusedHighlight">@color/color_coloredbackground</item>
<item name="android:colorActivatedHighlight">@color/color_coloredbackground</item>
<item name="android:activatedBackgroundIndicator">@color/color_coloredbackground</item>

这解决了我在任何列表视图中选择的背景颜色。我想这会对你有所帮助。

最新更新