[英]c# - Get specific value or posistion of selected spinner item
我有个问题。
我与一些客户创建了一个微调器。 微调器是根据包含4列的列表构建的:Id,名称,年龄,性别。 在微调器中,我创建了如下所示的项目:
ID:1-姓名:John-年龄:46-性别:男
ID:2-姓名:Micheal-年龄:32-性别:男
等等。
现在,我想要的是获取所选项目的ID,但是我无法弄清楚,因为我创建了一个自定义项目字符串。 因此,当我需要输入时,我当然会得到整个字符串。 我如何只获取字符串的ID并切断以下内容: “ Id:=>-名称:...-年龄:...-性别:...”因此,剩下的唯一是ID作为一个Int吗?
private void CustomerSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
SelectedSpinnerCustomer = spinner.GetItemAtPosition(e.Position).ToString();
LoadCustomerInfo(SelectedSpinnerCustomer);
}
因此,为了清楚起见,我希望SelectedSpinnerCustomer为int。 我怎样才能做到这一点?
最好的方法是创建一个自定义的Spinner类,该类继承常规的spinner类并包含您的所有四个属性
public class MySpinner : Spinner
{
public int Id { get; set; }
public int Age { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
然后在事件中
private void CustomerSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
MySpinner spinner = sender as MySpinner;
int SelectedSpinnerCustomer = spinner.Id;
int age = spinner.Age;
string name = spinner.Name;
string gender = spinner.Gender;
}
string
类中可以使用几种不同的方法。 这是一个经过简化的方法,并使用了多种字符串方法。
//Save the string in a local variable with a short name for better readability
string str = spinner.GetItemAtPosition(e.Position).ToString();
//Split the string by the underscores ('-')
string[] splitted = str.Split("-");
//Now you have a string array with all the values by themselves
//We know that ID is the first element in the array since your string starts with the ID
//So save it in a new string
string idStr = splitted[0];
//idStr is now "id: x "
//Remove the spaces by replacing them with nothing
idStr = idStr.Replace(" ", "");
//idStr is now "id:x"
//To get only 'x' we need to remove "id:" which can be done in multiple ways
//In this example I will use String.Remove() method
//Start at index 0 and remove 3 characters. This will remove "id:" from "id:x"
idStr = idStr.Remove(0, 3);
//Now idStr is "x" which is an integer, so we can just parse it
int id = int.Parse(idStr);
//Now you have the id as an integer!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.