简体   繁体   中英

Accessing list in adapter

Currently I am using C# with Xamarain and am developing for android. What I have right now is an activity (activity_MainView2) which holds a listview and has an adapter attached (adapter_MainView2). I also have a list (gCartList) which is inside of the activity, that I want to be able to access inside of the adapter to add the row id that the user clicks on. I have the onClick listeners set up inside of the adapter, but I'm not sure how to access the list. Sorry I'm pretty new to c#. Thank you in advance for the help.

From Activity

public List<Cart_List> gCartList { get; set; } = new List<Cart_List>();

When the cart button is press in the activity

public override bool OnOptionsItemSelected(IMenuItem item) { if (gDrawerToggle.OnOptionsItemSelected(item)) { return true; } else { switch (item.ItemId) { case Resource.Id.cartButton: Toast.MakeText(this, ("Cart Pressed").ToString(), ToastLength.Short).Show();

                   foreach (var tI in gCartList.OrderBy(a => a.Busn_ID)) System.Diagnostics.Debug.Write(tI);
                    return true;
            }
        }
        return base.OnOptionsItemSelected(item);
    } 

In the Adapter

activity_MainView2 act = new activity_MainView2(); var things = act.gCartList; things.Add(new Cart_List() { Busn_ID = "1", Item_ID = gItems[position].ID, Item_Qty = "1", Item_Name = gItems[position].Name, Item_Desc = gItems[position].Description, Item_Price = gItems[position].Price });

You can create a property in your activity and then it can be accessed like this:

public class Activity1
{
    pubic Activity1()
    {
        this.SomeThings = new List<object>();
    }
    public List<object> SomeThings { get; set; }
}

public class Activity2
{
    public Activity2()
    {
        // Now in this clas you can access the item to be shared
        Activity1 act = new Activity1();
        var things = act.SomeThings;
    }
}

Or you can pass it to the constructor like this:

public class Activity2
{
    private List<object> somethings;
    public Activity2(List<object> somethings)
    {
        // 
        this.somethings = somethings;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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