Search code examples
c#androidxamarinxamarin.android

How to update values and selected index in Alert Dialog builder setSingleChoiceItems


This is the adapter that i am using and you can see my view inflating from custom layout and the problem here is that after clicking/pressing an item, it wont process to my Item_Selected method thats why I added a custom onClick but the problem is that I wont close the spinner after click. Badly needs help

{
    public class CustomSpinnerAdapter : ArrayAdapter<String> {

        String type = String.Empty;
        List<string> orderList = new List<string>();
        Context context;
        PageTaskSearchView pageTaskSearchView = new PageTaskSearchView();
        String WCName = String.Empty;
        Bundle utilBundle;
        View viewPageTask;


        /// <summary>
        /// CUstom Spinner Array Adapter constructor
        /// </summary>
        /// <returns></returns>
        public CustomSpinnerAdapter(Context context, int textViewResourceId, List<String> objects, String type, Bundle utilBundle, View view)
                : base(context, textViewResourceId, objects) {
            this.type = type;
            this.orderList = objects;
            this.context = context;
            this.utilBundle = utilBundle;
            this.viewPageTask = view;
        }

        /// <summary>
        /// returns the total array count minus one
        /// </summary>
        /// <returns>int</returns>
        public override int Count
        {
            get
            {
                return base.Count;
            }
        }

        public override View GetDropDownView(int position, View convertView, ViewGroup parent)
        {
            return getCustomView(position, convertView, parent);
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            return getCustomView(position, convertView, parent);
        }

        public View getCustomView(int position, View convertView, ViewGroup parent)
        {
            LayoutInflater inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
            var view = convertView;



            if (position == 0)
            {
                if(Constants.ORDER_LIST == type) {

                    view = inflater.Inflate(Resource.Layout.CustomSpinnerView, null, true);
                    Switch filterOrder = (Switch) view.FindViewById(Resource.Id.switch_filterOrder);

                    int isFiltered = utilBundle.GetInt(Constants.ORDER_SWITCH_TRIGGER, 0);
                    filterOrder.Checked = Constants.ORDER_SWITCH_CLOSED == isFiltered;

                    filterOrder.CheckedChange += delegate (object sender, CompoundButton.CheckedChangeEventArgs e)
                    {
                        int filterStatus = e.IsChecked ? Constants.ORDER_SWITCH_CLOSED : 0;
                        utilBundle.PutInt(Constants.ORDER_SWITCH_TRIGGER, filterStatus);
                        String workCenter = utilBundle.GetString(Constants.WCName, Constants.EMPTY_STRING);
                        orderList = pageTaskSearchView.retrieveOrderlist(workCenter);

                        base.Clear();
                        base.AddAll(orderList);
                        base.NotifyDataSetChanged();

                    };

                }

                else
                {
                        LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(0, 0);
                        view = base.GetDropDownView(position, convertView, parent);
                        TextView tv = (TextView)view;
                        tv.SetHeight(0);
                        tv.LayoutParameters = layoutparams;
                        tv.Visibility = ViewStates.Gone;
                        view = tv;
                }
            }
            else
            {
                if (Constants.ORDER_LIST == type)
                {
                    view = inflater.Inflate(Resource.Layout.ListItemWithCheckbox, parent, false);
                    LinearLayout layout = (LinearLayout)view.FindViewById(Resource.Id.orderLayout);
                    TextView orderId = (TextView)view.FindViewById(Resource.Id.listItem);

                    RadioButton selected = view.FindViewById<RadioButton>(Resource.Id.checkedRadio);
                    selected.Checked = utilBundle.GetString(Constants.SELECTED_ORDER_ID, Constants.EMPTY_STRING).Equals(orderList[position]);
                    orderId.Text = orderList[position];

                    return view;

                    //view.Click += delegate (object sender, EventArgs e)
                    //{
                    //    PageTaskSearchViewModel pageTaskSearchViewModel = new PageTaskSearchViewModel(this.Context, this.viewPageTask, null, utilBundle);
                    //    pageTaskSearchViewModel.setOrderText(orderList[position]);
                    //};


                }
                else
                {
                    view = base.GetDropDownView(position, null, parent);

                }
            }

            parent.VerticalScrollBarEnabled = false;
            return view;

        }
    }
}

This is my item selected method, but after pressing an item, it wont proceed to this method.

    spinnerSelected = (TextView)view.FindViewById(Resource.Id.inp_workOrder);
                    String selected = (String)spinner.GetItemAtPosition(e.Position);
                    spinnerSelected.Text = selected;

Solution

  • Your CustomSpinnerAdapter can contain a Update method to reload data for adapter as follow :

    public class CustomSpinnerAdapter : BaseAdapter 
    {
        Context context;
        List<string> list;
    
        public CustomSpinnerAdapter(Context context, List<string> list)
        {
            this.context = context;
            this.list = new List<string>();
            this.list.AddRange(list) ;
        }
    
        public override Java.Lang.Object GetItem(int position)
        {
            return list[position];
        }
    
        public void Update(List<string> newList)
        {
            list.Clear();
            list.AddRange(newList);
            NotifyDataSetChanged();
        }
    
        public override long GetItemId(int position)
        {
            return position;
        }
    
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            //return base.GetDropDownView(position, convertView, parent);
            var view = convertView;
            CustomSpinnerAdapterViewHolder holder = null;
    
            if (view != null)
                holder = view.Tag as CustomSpinnerAdapterViewHolder;
    
            if (holder == null)
            {
                holder = new CustomSpinnerAdapterViewHolder();
                var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();
                //replace with your item and your holder items
                //comment back in
                view = inflater.Inflate(Resource.Layout.Itemlayout, parent, false);
                holder.Title = view.FindViewById<TextView>(Resource.Id.textView1);
                view.Tag = holder;
                holder.Title.Text = GetItem(position).ToString();
            }
            //fill in your items
    
    
            return view;
        }
    
        public override View GetDropDownView(int position, View convertView, ViewGroup parent)
        {
            //return base.GetDropDownView(position, convertView, parent);
            var view = convertView;
            CustomSpinnerAdapterViewHolder holder = null;
    
            if (view != null)
                holder = view.Tag as CustomSpinnerAdapterViewHolder;
    
            if (holder == null)
            {
                holder = new CustomSpinnerAdapterViewHolder();
                var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();
                //replace with your item and your holder items
                //comment back in
                view = inflater.Inflate(Resource.Layout.layoutDrop, parent, false);
                holder.Title = view.FindViewById<TextView>(Resource.Id.textView1);
                view.Tag = holder;
                holder.Title.Text = list[position];
            }
            //fill in your items
    
    
            return view;
        }
    
        //Fill in cound here, currently 0
        public override int Count
        {
            get
            {
                return list.Count;
            }
        }
    
    }
    
    class CustomSpinnerAdapterViewHolder : Java.Lang.Object
    {
        //Your adapter views to re-use
        public TextView Title { get; set; }
    }
    

    In Activity , init CustomSpinnerAdapter for Spinner :

    customAdapter = new CustomSpinnerAdapter(this, planetNames);
    spinner.Adapter = customAdapter;
    spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected);
    

    Then in ItemSelected method , when modifying data , you can invoke Update Method :

    private void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
        Spinner spinner = (Spinner)sender;
        string toast = string.Format("The planet is {0}", spinner.GetItemAtPosition(e.Position));
        Toast.MakeText(this, toast, ToastLength.Long).Show();
    
        if (isFirstShow)
        {
            isFirstShow = false;
            return;
        }
    
        Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
        Android.App.AlertDialog alert = dialog.Create();
        alert.SetTitle("Title");
        alert.SetMessage("Change data for spinner !");
        alert.SetButton("OK", (c, ev) =>
        {
            // Ok button click task  
            planetNames[e.Position] = "new data";
            customAdapter.Update(planetNames);
            Console.WriteLine("Modified!");
        });
        alert.Show();
    }
    

    The effect as follow :

    enter image description here

    ================================Update==================================

    Itemlayout.xml : Spinner undropdown view

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:text="getView()"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="25px"
            android:minHeight="25px"
            android:id="@+id/textView1"/>
    
    </LinearLayout>
    

    layoutDrop.xml : Spinner Dropdown view

    <RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="getDropDownView()"
            android:textSize="18sp"
            android:textColor="#ff0000" />
    
    </RelativeLayout >