更改Android上的Xamarin.Forms Listview中的默认TextColor

时间:2016-06-21 13:14:05

标签: listview xamarin xamarin.android xamarin.forms android-styles

我正在尝试更改Andoid上的Xamarin.Forms ListView中的默认TextColor

ListView非常简单:

List<string> cities = new List<string> { "Berlin", "Bonn", "Braunschweig", "Bremen" };
ListView listView = new ListView();
listView.ItemsSource = cities;
Content = listView;

在设备上它看起来像这样:

enter image description here

我想知道的是,TextColor将是黑色的。 据我了解Xamarin Forms CustomRenderer,每个项目都会生成Android.Resource.Layout.SimpleListItem1

SimpleListItem1使用以下textAppearance:

android:textAppearance="?android:attr/textAppearanceListItemSmall"

textAppearanceListItemSmall使用属性textAppearanceMedium进行渲染,您可以看到here

所以我已经将颜色和主题添加到资源中:

<?xml version="1.0" encoding="UTF-8" ?>
<resources>
  <color name="Black">#000000</color>
</resources>


<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <style name="MyTheme" parent="android:Theme.Holo.Light">
    <item name="android:textAppearanceMedium">@style/MyDefaultTextAppearanceM</item>
  </style>

  <style name="MyDefaultTextAppearanceM" parent="@android:style/TextAppearance.Medium">
    <item name="android:textColor">@color/Black</item>
  </style>
</resources>

我还将主题添加到我的活动属性(Theme = "@style/MyTheme) 主题基本上是有效的。使用<item name="android:colorActivatedHighlight">@color/Blue4</item>,我可以更改HighlightColor。

那么如何才能将ListView中的文本颜色变为黑色?我做错了什么?

3 个答案:

答案 0 :(得分:5)

尝试在设置内容之前添加此内容:

var template = new DataTemplate(typeof(TextCell));
template.SetValue(TextCell.TextColorProperty, Color.Black);
listView.ItemTemplate = template;

答案 1 :(得分:0)

谈话的后期,但也许其他人会在路上。

基于Xaml的解决方案,非常简单 - 只需在ImageCell上设置TextColor即可。像这样:

    <ContentPage.Content>
        <StackLayout VerticalOptions="FillAndExpand">
            <ListView x:Name="listView" VerticalOptions="FillAndExpand"
                SeparatorVisibility="None">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ImageCell TextColor="Black" Text="{Binding Title}"
                            ImageSource="{Binding IconSource}"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

答案 2 :(得分:0)

[assembly: ExportRenderer(typeof(MyTextCell), typeof(MyTextCellRenderer))]
namespace MyNamespace.Droid.Renderers
{
    public class MyTextCellRenderer : TextCellRenderer
    {
        protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
        {
            Android.Views.View result =  base.GetCellCore(item, convertView, parent, context);

            (result as BaseCellView).SetDefaultMainTextColor(Color.Black);

            return result;
        }
    }
}