listviewxamarin.androidtextviewadaptergetview

How to change single position in ListView with TextView


My code seems good but don't work

It is my xaml list possition definition: ListItemCenter

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center_vertical"
    android:layout_width="fill_parent"
    android:id ="@+id/linear_layout_center"
    android:layout_height="fill_parent">
<!-- Defining where should text be placed. You set you text color here-->
    <TextView
        android:id="@+id/list_content_center"
        android:textColor="@android:color/black"
        android:gravity="center"
        android:text="sample"
        android:textSize="20dp"
        android:layout_margin="4dip"
        android:layout_width="fill_parent"
        android:textStyle="bold"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:contextClickable="false"
        android:focusable="false"
        android:textColorHighlight="@android:color/black" />
</LinearLayout>

In my code

ArrayAdapter<string> content_adapter = new ArrayAdapter<string>(this, Resource.Layout.ListItemCenter, Resource.Id.list_content_center, content_tab);
TextList.Adapter = content_adapter;

// Here listview work fine

LinearLayout linlay = (LinearLayout)TextList.Adapter.GetView(4, null, TextList);                // here i have LinearLayout objec - it work
TextView mTextView = (TextView)linlay.FindViewById(Resource.Id.list_content_center);        // here i heve TextView object - it also work

mTextView.SetTextColor(Color.Red);          // dont work
mTextView.Gravity = GravityFlags.Left;          // properties is changed but list is still the same

Solution

  • How to change single possition in ListView with TextView

    You could custom a ArrayAdapter to implement this feature:

    public class MyAdapter : ArrayAdapter<string>
    {
        public MyAdapter(Context context, int resource, int textViewResourceId, string[] objects) : base(context, resource, textViewResourceId, objects)
        {
        }
    
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view = base.GetView(position, convertView, parent);
            TextView textView = view.FindViewById<TextView>(Resource.Id.list_content_center);
            if(position == 4)
            {
                textView.SetTextColor(Color.Red);
                textView.Gravity = GravityFlags.Left;
            }
            return view;
        }
    }
    

    Then you could use this ArrayAdapter as usual :

    MyAdapter content_adapter = new MyAdapter(this, Resource.Layout.ListItemCenter, Resource.Id.list_content_center, content_tab);
    TextList.Adapter = content_adapter;
    

    Effect like this.