Android spinner inside a custom control - OnItemSelectedListener does not trigger

Posted by Idan on Stack Overflow See other posts from Stack Overflow or by Idan
Published on 2012-11-04T22:32:27Z Indexed on 2012/11/04 23:00 UTC
Read the original article Hit count: 288

Filed under:
|
|

I am writing a custom control that extends LinearLayout. Inside that control I am using a spinner to let the user select an item from a list. The problem I have is that the OnItemSelectedListener event does not fire. When moving the same code to an Activity/Fragment all is working just fine.

I have followed some answers that was given to others asking about the same issue, and nothing helped. still the event does not fire.

This is my code after I followed the answers that suggested to put the spinner inside my layout XML instead of by code. I am getting the same result when I try to just "new Spinner(ctx)"...

layout XML:

  <Spinner
    android:id="@+id/accSpinner"        
    android:layout_width="0dip"
    android:layout_height="0dip" />

Initialization function of the control (called on the control constructor):

private void init()
{
    LayoutInflater layoutInflater = LayoutInflater.from(mContext);
    mAccountBoxView = layoutInflater.inflate(R.layout.control_accountselector, null);

    mTxtAccount = (TextView)mAccountBoxView.findViewById(R.id.txtAccount);
    mSpinner = (Spinner)mAccountBoxView.findViewById(R.id.accSpinner);

    mAccountBoxView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mSpinner.performClick();
            }
        });

    setSpinner();
    addView(mAccountBoxView);
}

private void setSpinner()
{       
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mItems);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);             
    mSpinner.setAdapter(dataAdapter);

    mSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                String selectedItem = mItems.get(position);
                handleSelectedItem(selectedItem);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent)
            {

            }
        });     
}

The spinner raises just fine when i touch my control and the list of items is there as it should. When I click an item the spinner closes but I am never getting to onItemSelected nor onNothingSelected..

Any ideas?

© Stack Overflow or respective owner

Related posts about java

Related posts about android