I have 2 comboboxes with 2 categories and 2 types of subcategories. Combobox categories contain "Usia" and "Serial". Whereas the subcategory combobox retrieves data from the json server. If you select "Usia" in the combobox category, it will display "ratingBox" in the combobox subcategory, and if you select "Serial" in the combobox category, it will display "serialBox" in the combobox subcategory.
XAML:
<StackPanel x:Name="comboBoxStack" Grid.Row="0" Margin="30,15,0,0" Orientation="Horizontal">
<ComboBox x:Name="kategoriBox" PlaceholderText="Kategori" FontSize="14" SelectionChanged="KategoriBox_SelectionChanged">
<ComboBoxItem>Usia</ComboBoxItem>
<ComboBoxItem>Serial</ComboBoxItem>
</ComboBox>
<ComboBox x:Name="ratingBox" Margin="15,0,0,0" PlaceholderText="Pilih Usia" ItemsSource="{x:Bind RatingList}" FontSize="14" SelectionChanged="RatingBox_SelectionChanged"/>
<ComboBox x:Name="serialBox" Margin="15,0,0,0" PlaceholderText="Pilih Serial" ItemsSource="{x:Bind SerialList}" FontSize="14" SelectionChanged="SerialBox_SelectionChanged"/>
</StackPanel>
Code:
List<Rating> RatingList = new List<Rating>();
List<Serial> SerialList = new List<Serial>();
string umurID = "";
string serialID = "";
private void KategoriBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBoxItem = kategoriBox.Items[kategoriBox.SelectedIndex] as ComboBoxItem;
if (comboBoxItem != null)
{
string selectedcmb = comboBoxItem.Content.ToString();
if(selectedcmb == "Usia")
{
ratingBox.Visibility = Visibility.Visible;
serialBox.Visibility = Visibility.Collapsed;
RatingC();
ratingBox.SelectedIndex = -1;
}
else if(selectedcmb == "Serial")
{
ratingBox.Visibility = Visibility.Collapsed;
serialBox.Visibility = Visibility.Visible;
SerialC();
serialBox.SelectedIndex = -1;
}
}
else
{
ratingBox.Visibility = Visibility.Visible;
serialBox.Visibility = Visibility.Collapsed;
RatingC();
}
}
private async void RatingC()
{
serialID = "";
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
try
{
string urlPath = "https://..../Fetch/rating";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["rating"].GetString();
Rating rate = new Rating();
rate.ID = id;
rate.Name = name;
RatingList.Add(new Rating()
{
ID = rate.ID,
Name = rate.Name
});
}
}
catch
{
busyindicator.IsActive = false;
}
}
}
private async void SerialC()
{
umurID = "";
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
try
{
string urlPath = "https://.../Fetch/serial";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["nama"].GetString();
string slug = groupObject1["slug"].GetString();
Serial seri = new Serial();
seri.ID = id;
seri.Name = name;
seri.Slug = slug;
SerialList.Add(new Serial()
{
ID = seri.ID,
Name = seri.Name,
Slug = seri.Slug
});
}
}
catch
{
busyindicator.IsActive = false;
}
}
}
private void RatingBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(ratingBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Rating value = comboBox.SelectedItem as Rating;
umurID = value.ID;
}
}
private void SerialBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(serialBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Serial value = comboBox.SelectedItem as Serial;
serialID = value.ID;
}
}
Rating.cs:
class Rating
{
public string ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
}
Serial.cs same as Rating.cs
I have a problem, that is if I have chosen "Usia" in the combobox category, then the combobox subcategory for that category can display data on the server smoothly, then I choose "Serial" in the combobox category, eating combobox subcategories for that category can display data on the server with smoothly. Then I again chose "Usia" in the combobox category, so when I click on the subcategory, an error message appears as shown below:
And here is my PC screen video for my problem:
https://1drv.ms/v/s!Auqiv8Ukng7UgP8Fj-LMDa9skV3yfA
In the video when re-selecting "Usia" in the combobox category (at the end of the video), it will display an error message as shown above
How to handle it?
Related
I have a Json from the server as below:
{
"data": {
"komik_popular": {
"title": "Yei! Komik Awas Nyamuk Jahat jadi literasi terpopuler minggu ini lho!"
},
"buku_baru": {
"title": "Ada buku baru nih, Katalog Prasekolah"
}
},
}
I want to display the json on the listview, but I try Debug.Writeline("judul: " + highlight.Title) first
Code:
Highlight highlight = new Highlight();
string title = "";
string urlPath = link;
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("SCH-API-KEY", "SCH_KEnaBiDeplebt")
};
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
string jsonText = await response.Content.ReadAsStringAsync();
try
{
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject jsonData = jsonObject["data"].GetObject();
JsonObject bukuBObject = jsonData.ContainsKey("buku_baru") && jsonData["buku_baru"] != null ? jsonData["buku_baru"].GetObject() : JsonObject.Parse("");
try
{
title = bukuBObject["title"].GetString();
}
catch
{
}
JsonObject komikPObject = jsonData.ContainsKey("komik_popular") && jsonData["komik_popular"] != null ? jsonData["komik_popular"].GetObject() : JsonObject.Parse("");
try
{
title = komikPObject["title"].GetString();
}
catch
{
}
highlight.Title = title;
Debug.WriteLine("judul: " + highlight.Title);
}
Highlight.cs:
class Highlight
{
public string Title { get; set; }
}
I'm having a problem, when I try to debug only the title on "komik_popular" is displayed, I want all the data in "komik_popular" and "buku_baru" to be displayed. How to handle it?
private List<Highlight > HighlightList = new List<Highlight>();
string urlPath = link;
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("SCH-API-KEY", "SCH_KEnaBiDeplebt")
};
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
string jsonText = await response.Content.ReadAsStringAsync();
try
{
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonObject jsonData = jsonObject["data"].GetObject();
JsonObject komikPObject = jsonData.ContainsKey("komik_popular") && jsonData["komik_popular"] != null ? jsonData["komik_popular"].GetObject() : JsonObject.Parse("");
try
{
Highlight highlight = new Highlight();
string title = "";
title = komikPObject["title"].GetString();
HighlightList.Add(highlight);
}
catch
{
}
JsonObject bukuBObject = jsonData.ContainsKey("buku_baru") && jsonData["buku_baru"] != null ? jsonData["buku_baru"].GetObject() : JsonObject.Parse("");
try
{
Highlight highlight = new Highlight();
string title = "";
title = bukuBObject["title"].GetString();
HighlightList.Add(highlight);
}
catch
{
}
}
catch
{
}
foreach( Highlight items in HighlightList)
{
Debug.WriteLine("judul: " + items .Title);
}
}
for converting json data to list, first you have to create respective class model as per given data format after that you can convert or deserialize it in your list format , in cae of your json data you can follow below example :-
public class Titel
{
public string title { get; set; }
}
public class Data
{
public Titel komik_popular { get; set; }
public Titel buku_baru { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
class Program
{
static void Main(string[] args)
{
string s = "{'data':{'komik_popular':{'title':'Yei! Komik Awas Nyamuk Jahat jadi literasi terpopuler minggu ini lho!'},'buku_baru':{'title':'Ada buku baru nih, Katalog Prasekolah'}}}";
List<RootObject> dataList = JsonConvert.DeserializeObject<List<RootObject>>(s);
}
}
I have a combobox category with 2 items ('usia' and 'serial') and when a user selects one item, for example: serial, it will display binding combobox containing serial subcategories.
XAML:
<ComboBox x:Name="kategoriBox" PlaceholderText="Kategori" FontSize="14" SelectionChanged="KategoriBox_SelectionChanged" Background="{x:Null}" BorderBrush="{x:Null}">
<ComboBoxItem>Usia</ComboBoxItem>
<ComboBoxItem>Serial</ComboBoxItem>
</ComboBox>
<ComboBox x:Name="usiaBox" PlaceholderText="Pilih Usia" ItemsSource="{x:Bind RatingList}" FontSize="14" SelectionChanged="UsiaBox_SelectionChanged" Background="{x:Null}" BorderBrush="{x:Null}"/>
<ComboBox x:Name="serialBox" Margin="15,0,0,0" PlaceholderText="Pilih Serial" ItemsSource="{x:Bind SerialList}" FontSize="14" SelectionChanged="SerialBox_SelectionChanged" Background="{x:Null}" BorderBrush="{x:Null}"/>
Code:
private void KategoriBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedcmb = ((ComboBoxItem)kategoriBox.SelectedItem).Content.ToString();
if (selectedcmb == "Usia")
{
UsiaC();
usiaBox.Visibility = Visibility.Visible;
serialBox.Visibility = Visibility.Collapsed;
}
else if (selectedcmb == "Serial")
{
SerialC();
usiaBoX.Visibility = Visibility.Collapsed;
serialBox.Visibility = Visibility.Visible;
}
}
private async void UsiaC()
{
try
{
string urlPath = "https://..../api-v3/Fetch/rating";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["rating"].GetString();
Rating rate = new Rating();
rate.ID = id;
rate.Name = name;
RatingList.Add(new Rating()
{
ID = rate.ID,
Name = rate.Name
});
}
}
catch(Exception)
{
busyindicator.IsActive = false;
umurID = "";
}
}
}
private async void SerialC()
{
try
{
string urlPath = "https://.../api-v3/Fetch/serial";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
};
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("SCH-API-KEY", "SCH_KEnaBiDeplebt");
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
busyindicator.IsActive = false;
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue in jsonData)
{
JsonObject groupObject1 = groupValue.GetObject();
string id = groupObject1["id"].GetString();
string name = groupObject1["nama"].GetString();
string slug = groupObject1["slug"].GetString();
Serial seri = new Serial();
seri.ID = id;
seri.Name = name;
seri.Slug = slug;
SerialList.Add(new Serial()
{
ID = seri.ID,
Name = seri.Name,
Slug = seri.Slug
});
}
}
catch(Exception)
{
busyindicator.IsActive = false;
serialID = "";
}
}
}
private void UsiaBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (usiaBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Usia value = comboBox.SelectedItem as Rating;
usiaID = value.ID;
serialID = "";
}
else
{
usiaID = "";
}
}
private void SerialBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(serialBox.SelectedIndex != -1)
{
var comboBox = sender as ComboBox;
Serial value = comboBox.SelectedItem as Serial;
serialID = value.ID;
usiaID = "";
}
else
{
serialID = "";
}
}
Usia.cs
class Usia
{
public string ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
}
Serial.cs
class Serial
{
public string ID { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public override string ToString()
{
return this.Name;
}
}
I have a problem, namely: I chose 'serial' on the category combobox then chose the subcategory. Then I chose 'usia' on the combobox category then chose the subcategory. Then I re-select 'serial' on the category and click the subcategory, then an error message will appear as shown below:
How to handle it?
I have a list of information that comes from an API.
I want to filter out certain things for a ListBox. I have made a public string for this and added the information I wanted in the list.
Now the way I have it set up it shows the information I would like, but leaves empty spaces in the ListBox.
I want to get rid of this spaces in the ListBox. I have tried to return a null and a string.Empty
get
{
if( Status == 1)
{
string queues = $"{SSDocument.SSDocumentID} | {LastActionUser} | {LastAccessed} | {Queue.Name}";
return queues;
}
else
{
return null;
}
}
Information using the GET:
public void DocumentList(int sender)
{
if (sender == 1)
{
StatusList f = new StatusList();
f.Show();
st = rClient.makeRequest(S9());
f.listBox1.DataSource = st;
f.listBox1.DisplayMember = "QueueList";
}
}
Request for rClient.makeRequest(s9()):
public List<stats> makeRequest(string endPoint)
{
signOn so = new signOn();
string strResponseVlaue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
request.Method = "GET";
string userName = so.grabUser();
string passWord = so.grabPass();
string domain = System.Configuration.ConfigurationManager.AppSettings["Domain"];
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"{domain}{userName}:{passWord}"));
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Error Code: " + response.StatusCode.ToString());
}
//Process the response stream
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseVlaue = reader.ReadToEnd();
}
}
} //End of Response Stream
}// End Of Using Reponse
var obj = JsonConvert.DeserializeObject<List<stats>>(strResponseVlaue);
return obj;
}
The getter of a class property used as the DisplayMember of a ListBox control, tries to filter out the elements that do not satisfy a condition.
The condition is verified in the property getter, forcing to return null or string.Empty when the current element doesn't satisfy the condition.
This behaviour produces empty elements in the ListBox.
The proposed solution is, of course, to pre-filter the elements that define the ListBox data source before the property used as DisplayMember, can format the elements to display:
[ListBox].DataSource = st.Where(cls => [Condition]).ToList();
A probaly better solution is to build a class that can perform the filtering on its own.
An example:
int Sender = 1;
TestClass test = new TestClass();
test.AddRange(new []
{
new TestClass() { Status = 0, QueueName = "Queue1", SSDocumentID = 1 },
new TestClass() { Status = 1, QueueName = "Queue1", SSDocumentID = 1 },
new TestClass() { Status = 1, QueueName = "Queue2", SSDocumentID = 2 },
new TestClass() { Status = 0, QueueName = "Queue3", SSDocumentID = 3 },
new TestClass() { Status = 1, QueueName = "Queue4", SSDocumentID = 4 },
});
listBox1.DisplayMember = "DisplayMember";
listBox1.DataSource = test.Filter(Sender).ToList();
public class TestClass
{
public TestClass() => this.Members = new List<TestClass>();
public int Status { get; set; }
public int SSDocumentID { get; set; }
public string QueueName { get; set; }
public string DisplayMember => $"{this.SSDocumentID} | {this.QueueName}";
public List<TestClass> Members { get; }
public void Add(TestClass element) => this.Members.Add(element);
public void AddRange(IEnumerable<TestClass> elements) =>
this.Members.AddRange(elements.ToArray());
public IEnumerable<TestClass> Filter(int status)
{
if (this.Members.Count == 0) return null;
return this.Members.Where(st => st.Status == status);
}
}
I have a collection ConversationModel that have two models in it. I want to get the value of the very first item of the collection. I tried this code var obj = ConversationCollection.First(); to get the value but it always returns null. Here the model's property is populated but outside of it. How can I get those values
public class ConversationModel
{
public SendMessageModel SMM { get; set; }
public ReceivedMessageModel RMM { get; set; }
}
Here's how I create my collection:
ObservableCollection<ConversationModel> cm = new ObservableCollection<ConversationModel>();
foreach (DataRow convo in dataTable.Rows)
{
string _messageID = (string)convo["MessageID"];
string message = (string)convo["UserMessage"];
string username = (string)convo["FromUser"];
DateTime datetime = (DateTime)convo["MessageDateTime"];
string messageStatus = (string)convo["MessageStatus"];
string mdt = "";
if (datetime.Date == DateTime.Now.Date) mdt = datetime.ToString("t");
if (username == ClientUsername)
{
SendMessageModel smm = new SendMessageModel
{
MessageIdentifier = _messageID,
UserDisplayName = ClientDisplayName,
SendMessage = message,
MessageTime = mdt,
MessageStatus = (Status)Enum.Parse(typeof(Status), messageStatus)
};
cm.Add(new ConversationModel { SMModel = smm });
}
else
{
ReceivedMessageModel rmm = new ReceivedMessageModel
{
MessageIdentifier = _messageID,
ClientDisplayName = RecipientDisplayName,
MessageTime = mdt,
ReceivedMessage = message
};
cm.Add(new ConversationModel { RMM = rmm });
}
}
ConversationCollection = cm;
My WPF Code for the ItemsControl
<ItemsControl ItemsSource="{Binding ConversationCollection}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type Models:ReceivedMessageModel}">
<UserControls:RecievedMessageBubble/>
</DataTemplate>
<DataTemplate DataType="{x:Type Models:SendMessageModel}">
<UserControls:SendMessageBubble />
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
If ConversationCollection is an ObservableCollection<ConversationModel>, it can only contain ConversationModels which is why neither of your data templates will be applied.
If you change its type to for example ObservableCollection<object>, you could add both ReceivedMessageModels and SendMessageModels to it.
You will then be able to retrive the first item by casting:
var receivedMessageModel = ConversationCollection[0] as ReceivedMessageModel;
if (receivedMessageModel != null)
{
//the first item is a ReceivedMessageModel
}
else
{
var sendMessageModel = ConversationCollection[0] as SendMessageModel;
// the first item is A SendMessageModel
}
Hello someone could help me please, I am making an application in Xamarin android as a project at school, but I have doubts with a checkbox and RecyclerView, what happens is that it assumes that the user can select one or more item within the RecyclerView and when push a poton that btnagregar save all the item name having the Checked property to true in a mysql database
MenuItemA.cs
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecycleAdapter mAdapter;
List<ItemAli> alilist;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
new I18N.West.CP1250();
new I18N.CJK.CP50220();
int idC = Convert.ToInt32(Intent.GetStringExtra("idc") ?? "Data not available");
SetContentView(Resource.Layout.RecyclerItem);
alilist = new List<ItemAli>();
try
{
string connsqlstring = "";
MySqlConnection sqlconn = new MySqlConnection(connsqlstring);
sqlconn.Open();
DataSet ds = new DataSet();
string queryString = "SELECT `IdAli`, `NombreA`, `Precio`, `Imagen`, `Tiempo` FROM `alimentos` as Item WHERE `IdCategoria` = " + idC;
MySqlDataAdapter adapter = new MySqlDataAdapter(queryString, sqlconn);
adapter.Fill(ds, "Item");
foreach (DataRow row in ds.Tables["Item"].Rows)
{
alilist.Add(new ItemAli { AliID = (row[0]).ToString(), Name = row[1].ToString(), Quantity = 0, Price = Convert.ToDecimal(row[2]), ImageId = row[3].ToString(), Time = row[4].ToString(), AddToOrder = false});
}
sqlconn.Close();
}
catch
{
Toast.MakeText(this, "La categoria esta vacia", ToastLength.Short).Show();
}
Button btnagregar = FindViewById<Button>(Resource.Id.btanadir);
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rvitem);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.SetLayoutManager(mLayoutManager);
mAdapter = new RecycleAdapter(this,alilist);
mAdapter.ItemClick += OnItemClick;
mAdapter.SpinnerItemSelectionChanged += SpinnerItemSelectionChangedEvent;
mRecyclerView.SetAdapter(mAdapter);
btnagregar.Click += delegate
{
};
}
void OnItemClick(object sender, string IdAlimento)
{
var a = new Intent(this, typeof(ActividadDetAli));
a.PutExtra("idA", IdAlimento);
StartActivity(a);
}
void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32 (spinner.Tag);
var currentquantity = alilist[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32( spinner.GetItemAtPosition (e.Position).ToString());
if (currentquantity != selectedQuantity) {
alilist [itemPosition].Quantity = selectedQuantity;
mAdapter.NotifyItemChanged (itemPosition);
}
}
}
RecycleAdapter.cs
public class VegeViewHolder: RecyclerView.ViewHolder
{
public ImageView Image { get; set; }
public TextView Name { get; set; }
public Spinner Quantity { get; set; }
public TextView Price { get; set; }
public TextView TotalAmount { get; set; }
public CheckBox cbx { get; set; }
public string idA { get; set; }
public VegeViewHolder(View itemView, Action<string> itemlistner, Action<object,AdapterView.ItemSelectedEventArgs> spinnerItemSelected )
:base(itemView)
{
Image = itemView.FindViewById<ImageView> (Resource.Id.list_image);
Name = itemView.FindViewById<TextView> (Resource.Id.Name);
Price = itemView.FindViewById<TextView> (Resource.Id.Price);
Quantity = itemView.FindViewById<Spinner> (Resource.Id.spinner1);
TotalAmount = itemView.FindViewById<TextView> (Resource.Id.total);
cbx = itemView.FindViewById<CheckBox>(Resource.Id.cbc);
itemView.Click += (sender, e) => itemlistner (idA);
Quantity.ItemSelected+= new EventHandler<AdapterView.ItemSelectedEventArgs> (spinnerItemSelected);
}
}
public class RecycleAdapter:RecyclerView.Adapter
{
public event EventHandler<string> ItemClick;
public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public List<ItemAli> Items;
Activity Context;
List<string> _quantity = new List<string> ();
public RecycleAdapter (Activity context, List<ItemAli> list)
{
this.Items = list;
this.Context = context;
PopulateSpinnerDropDownValues ();
}
void PopulateSpinnerDropDownValues()
{
_quantity.Add ("0");
_quantity.Add ("1");
_quantity.Add ("2");
_quantity.Add ("3");
_quantity.Add ("4");
_quantity.Add ("5");
_quantity.Add ("6");
_quantity.Add ("7");
_quantity.Add ("8");
_quantity.Add ("9");
_quantity.Add("10");
_quantity.Add("11");
_quantity.Add("12");
_quantity.Add("13");
_quantity.Add("14");
_quantity.Add("15");
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.list_items, parent, false);
VegeViewHolder vh = new VegeViewHolder(itemView, OnClick,spinner_ItemSelected);
return vh;
}
public override int ItemCount
{
get { return Items != null ? Items.Count : 0; }
}
void OnClick(string IdAlimento)
{
if (ItemClick != null)
ItemClick (this, IdAlimento);
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
if (SpinnerItemSelectionChanged != null)
SpinnerItemSelectionChanged (sender, e);
}
public Bitmap GetBitmapFromUrl(string url)
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(url);
if (bytes != null && bytes.Length > 0)
{
return BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
}
}
return null;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var item = Items[position];
var vh = viewHolder as VegeViewHolder;
var spinnerPos = 0;
var adapter =new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Precio: ${0}",item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0) {
spinnerPos = adapter.GetPosition (item.Quantity.ToString ());
vh.TotalAmount.Text = string.Format ("${0}", item.Price * item.Quantity);
} else {
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position;
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
Bitmap bitmap = GetBitmapFromUrl(item.ImageId);
vh.Image.SetImageBitmap(bitmap);
vh.idA = item.AliID +"°"+ item.ImageId + "°" + item.Name + "°" + item.Price + "°" + item.Time;
vh.cbx.Checked = item.AddToOrder;
}
}
}