Forum Xamarin Xamarin.Android

How populate a Spinner with Key/Value

Hi guys i wondering if anyody have a example or an idea about populate a spinner like combobox in VB.net/C#.net

Best Answer

Answers

  • Sam.27Sam.27 NZMember ✭✭
    edited November 2017

    You mean this?

        <Spinner
                                p1:textAppearance="?android:attr/textAppearanceSmall"
                                p1:layout_width="wrap_content"
                                p1:layout_height="wrap_content"
                                p1:layout_below="@+id/"
                                p1:id="@+id/someID"
                                p1:background="@android:drawable/btn_dropdown"
                                p1:layout_alignParentLeft="true"
                                p1:layout_alignParentRight="true"
                                p1:layout_marginLeft="10dp"
                                p1:layout_marginRight="10dp" />
    
    
    
      // code behind: 
    
    
        //Oncreate: 
    
                Spinner someID= FindViewById<Spinner>(Resource.Id.someID);
                someID.ItemSelected += new System.EventHandler<AdapterView.ItemSelectedEventArgs>(this.someID_ItemSelected);
    
    
                    ArrayAdapter someAdapter = new ArrayAdapter(this, Resource.Layout.SimpleSpinner, listStringValue);
                   someAdapter .SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                    someID.Adapter = someAdapter ;
                    someID.SetSelection(selectedindex);
    
    
            private void cbHAM1_Pieces_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
                {
        //Your code here
    
        }
    
  • RenegadoMVARenegadoMVA USMember ✭✭

    Hi Sam.27. thanks for you response i appreciate it.
    But im lookin for an example that include KEY/VALUE like DisplayMember/ValueMember in Winforms
    IN Xmarin.Android i being use this to populate, but it only contains membersValue

    ITEM 1
    ITEM 2
    ITEM 3
    ITEM 4
    ITEM 5
    ITEM 6

    but i looking for some like:


    <ítem value=1>ITEM 1
    <ítem value=2>ITEM 2
    <ítem value=3>ITEM 3
    <ítem value=4>ITEM 4
    <ítem value=5>ITEM 5
    <ítem value=6>ITEM 6

    then Access by SELECTED ITEM like

    spinner.SelectedItemPosition.ToString();
    or
    spinner.SelectedItemId

    something like that

    Sam,27, im new in Android and C#

    Thanks for your time.

  • RenegadoMVARenegadoMVA USMember ✭✭

    @Sam.27 said:
    You mean this?

        <Spinner
                                p1:textAppearance="?android:attr/textAppearanceSmall"
                                p1:layout_width="wrap_content"
                                p1:layout_height="wrap_content"
                                p1:layout_below="@+id/"
                                p1:id="@+id/someID"
                                p1:background="@android:drawable/btn_dropdown"
                                p1:layout_alignParentLeft="true"
                                p1:layout_alignParentRight="true"
                                p1:layout_marginLeft="10dp"
                                p1:layout_marginRight="10dp" />
        
        
        
      // code behind: 
        
              
        //Oncreate: 
                
                Spinner someID= FindViewById<Spinner>(Resource.Id.someID);
                someID.ItemSelected += new System.EventHandler<AdapterView.ItemSelectedEventArgs>(this.someID_ItemSelected);
        
        
                    ArrayAdapter someAdapter = new ArrayAdapter(this, Resource.Layout.SimpleSpinner, listStringValue);
                   someAdapter .SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                    someID.Adapter = someAdapter ;
                    someID.SetSelection(selectedindex);
        
        
            private void cbHAM1_Pieces_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
                {
        //Your code here
        
        }
    

    8:09AM

    Hi Sam.27. thanks for you response i appreciate it.
    But im lookin for an example that include KEY/VALUE like DisplayMember/ValueMember in Winforms
    IN Xmarin.Android i being use this to populate, but it only contains membersValue

    <ítem> ITEM 1<ítem>
    <ítem>ITEM 2<ítem>
    <ítem> ITEM 3<ítem>
    <ítem> ITEM 4<ítem>
    <ítem>ITEM 5<ítem>
    <ítem> ITEM 6<ítem>

    but i looking for some like:

    <ítem value=1>ITEM 1<ítem>
    <ítem value=2>ITEM 2<ítem>
    <ítem value=3>ITEM 3<ítem>
    <ítem value=4>ITEM 4<ítem>
    <ítem value=5>ITEM 5<ítem>
    <ítem value=6>ITEM 6<ítem>

    then Access by SELECTED ITEM like

    spinner.SelectedItemPosition.ToString();
    or
    spinner.SelectedItemId

    something like that

    Sam,27, im new in Android and C#

    Thanks for your time.

  • DimChrisDimChris USMember ✭✭✭✭
    Wha do you mean key/value? You mean to set two seperated values inside a spinner.Like name and id?
  • CortezCortez USMember ✭✭✭
    edited November 2017

    Hello @DimChris,
    Key/value means: if you have a class like

        class Gender
        {
        public int GenderId;
        public string GenderName;
        }
    

    and you want to populate a ComboBox in Windows Forms with a List<Gender> you can set the DataSource property with your genders and set the DisplayMember for showing GenderName in the dropdown and ValueMember for GenderId. So the ComboBox will show a gender, but when you select an item, you will get the id. This using Reflection, i think. This is one component (control/class) in Windows Forms, but in Xamarin the Spinner is only a view, a GUI element that show the elements and the adapter will handle the data. In this case @RenegadoMVA, you should implement an advanced adapter that will operate like this. It will have a DisplayMember, a ValueMember and a DataSource property. You can set the data source via this property instead in the constructor as third parameter. After setting the properties you have to use Reflection and get the definied values. You will provide the DisplayMember for the Spinner and the ValueMember for the selection.

    But i think this is too much effort. I would use Sam's solution instead. In the constructor i can set the "DisplayMember" by using a Linq Select() on the initial dataset and in the event handler from the position i can get the item.

  • DimChrisDimChris USMember ✭✭✭✭

    I'm looking now for the same thing. But i think that you can solve this by using tag in your spinner. I'm in front for making the same thing you ask. When i will solve this i will post you my solution

  • DimChrisDimChris USMember ✭✭✭✭
    edited November 2017

    DELETED

  • DimChrisDimChris USMember ✭✭✭✭
    edited November 2017

    Ok i think i found an easy example for doing this.

        [Activity(Label = "App1", MainLauncher = true)]
        public class MainActivity : Activity
        {
            Spinner spinner0;
            TextView textView0;
            string[] text0 = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
            int[] val1 = { 0, 1, 2, 3, 4, 5, 6 };
            protected override void OnCreate(Bundle savedInstanceState)
            {          
                base.OnCreate(savedInstanceState);
    
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);
    
                textView0 = FindViewById<TextView>(Resource.Id.text0);
                spinner0 = FindViewById<Spinner>(Resource.Id.spinner0);
    
                var adapter0 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, text0);
                spinner0.Adapter = adapter0;
                spinner0.ItemSelected += Spinner0_ItemSelected; ;
    
            }
            private void Spinner0_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
            {
                string s1 = val1[e.Position].ToString();
                textView0.Text = s1;
            }
        }
    

    XML FILE:

            <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.androidspinnertext.MainActivity">
        <Spinner
            android:id="@+id/spinner0"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/text0"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    

    So the only thing you have now to do is to fill each aray with your sqlite values.Example inside string[] //your keys and inside int[] your values

  • RenegadoMVARenegadoMVA USMember ✭✭

    @Cortez said:
    Hello @DimChris,
    Key/value means: if you have a class like

    class Gender
    {
    public int GenderId;
    public string GenderName;
    }

    and you want to populate a ComboBox in Windows Forms with a List<Gender> you can set the DataSource property with your genders and set the DisplayMember for showing GenderName in the dropdown and ValueMember for GenderId. So the ComboBox will show a gender, but when you select an item, you will get the id. This using Reflection, i think. This is one component (control/class) in Windows Forms, but in Xamarin the Spinner is only a view, a GUI element that show the elements and the adapter will handle the data. In this case @RenegadoMVA, you should implement an advanced adapter that will operate like this. It will have a DisplayMember, a ValueMember and a DataSource property. You can set the data source via this property instead in the constructor as third parameter. After setting the properties you have to use Reflection and get the definied values. You will provide the DisplayMember for the Spinner and the ValueMember for the selection.

    But i think this is too much effort. I would use Sam's solution instead. In the constructor i can set the "DisplayMember" by using a Linq Select() on the initial dataset and in the event handler from the position i can get the item.

    Hi @Cortez sorry to answer to late, but i was on vacation haha . but im back.
    Well, as you say, is very hard to made this "simple" but i gonna try with all the tips and examples that you can suggested me.

    I don´t know why Xamarin ( Microsoft) not keep the same way to DropDownList and Spinner.
    but i need more knowledgement to see if this possible :)

    Thank you!

  • RenegadoMVARenegadoMVA USMember ✭✭

    Hi again @DimChris sorry for answer you to late. but i was on my vacations hahaha.
    Excellent way to solve this @DimChris i gonna implement this in my project. so last question to you.

    To get the Val1 array value when i select the value of the textView, which is the best way to do this: when i click in a button, get the Value of var VAL1

    private void BRegistrar_Click(object sender, EventArgs e)
    {
    string strVal = Spinner0.SelectedItem.ToString();
    }
    
    private void BRegistrar_Click(object sender, EventArgs e)
    {
    string strVal = textView0.Text;
    }
    

    Best regards.

  • DimChrisDimChris USMember ✭✭✭✭
    edited December 2017

    If i am right, you want when you clicking the button to take the value from spinner?
    You can use the same method with key example: (name instead id)

    string s1 = Name[e.Position].ToString();
    

    Or another method which i prefer,

    Spinner Spn1= FindViewById<Spinner>(Resource.Id.categorytext); 
    String textview; 
    textview = Spn1.SelectedItem.ToString(); 
    
  • momemome Member ✭✭

    @DimChris said:
    Here is my example from sqlite to spinner key/value

                List<String> ID;
                List<String> Name;
                protected override void OnCreate(Bundle savedInstanceState)
                {
                    Name = new List<String>();
                    ID = new List<String>();
                    db = new SQLiteConnection(dpPath);
                    var table = db.Query<CategoryPreviewClass>("select * from CategoryPreviewClass");
                
                    foreach (var item in table)
                    {
                        Name.Add((string)item.CategoryName);
                        ID.Add((string)item.CategoryID);
                    }
        
                    var adapter0 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, Name);
                    spinner1.Adapter = adapter0;
                    spinner1.ItemSelected += Spinner1_ItemSelected;
                
                }
        
                private void Spinner1_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
                {
                    string s1 = ID[e.Position].ToString();
                    Toast.MakeText(this, s1, ToastLength.Short).Show();
                }
    

    This one worked for me too :-) thanks

Sign In or Register to comment.