spinner onitemselected is not working as expected?

1.5k views Asked by At

I did not add spinner on my layout

I did not use addView function

code

 Spinner spinner = new Spinner(MainActivity.this);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, myArray);
    spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
            {
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
                {
                    //this place is never called
                }

                public void onNothingSelected(AdapterView<?> parent) 
                {

                }
            });

I called spinner like this:

 spinner.performClick();

After this I click one of my item which in my array and then I expect to fire onItemSelected but it never fires.

the problem is

onitemselected is never called.

thanks in advance

2

There are 2 answers

5
Attiq ur Rehman On

In order to programatically select item from spinner. you need to call

spinner.setSelection(1);

Whereas 1 in the index, you want to select

2
Sachin Varma On

Try this,

1.Create a custom adapter.

2.set click Listener to textview in adapter.(so you can get position in adapter)

3.according to positon do whatever u feel like.

CustomModel.

public class CustomModel {
    private String id;
    private String description;

    public char[] name;

    public CustomModel() {

    }

    public CustomModel(String id, String description) {
        this.id = id;
        this.description = description;

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


    public String getName() {
        return description;
    }
    public void setName(String description) {
        this.description = description;
    }
}

Activity.

    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.CursorAdapter;
    import android.widget.LinearLayout;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;
    import java.util.List;

    import adapter.CustomAdapter;
    import models.CustomModel;
    import utils.SessionManager;

    import static android.R.attr.id;
    import static android.R.id.text1;

    public class spinner extends AppCompatActivity {

        private SessionManager sessionManager;
        private List<CustomModel> myArray=new ArrayList<CustomModel>();
        CustomModel customModel;
        LinearLayout container;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.spinnre);
            container = (LinearLayout) findViewById(R.id.container);
            customModel=new CustomModel();
            customModel.setName("Select a number");
            myArray.add(customModel);
            for(int i=0;i<10;i++)
            {
                customModel=new CustomModel();
                customModel.setName(String.valueOf(i));
                myArray.add(customModel);
            }
            LinearLayout.LayoutParams spinnerParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams textParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            spinnerParamas.setMargins(0,50,0,0);
            Spinner spinner = new Spinner(spinner.this);
            spinner.setLayoutParams(spinnerParamas);
            spinner.setId(0);
   CustomAdapter customAdapter=new CustomAdapter(spinner.this,myArray,spinner);            
          spinner.setAdapter(customAdapter);
            container.addView(spinner);
        }
    }

Adapter

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ciomp.global.R;

import models.CustomModel;

/**
 * Created by ciomp on 11/23/2016.
 */

public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    private List<CustomModel> mList=new ArrayList<CustomModel>();
    private LayoutInflater mLayoutInflater;
    private String mType=null;
    private Spinner mSpinner;
    int one=0;


    public CustomAdapter(Context mContext, List<CustomModel> list, Spinner spin) {
        this.mContext=mContext;
        this.mList=list;
        mSpinner=spin;

    }


    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        CustomAdapter.ViewHolder holder=null;
        LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if(convertView==null){
            convertView = layoutInflater.inflate(R.layout.customlayout, null);
            holder = new CustomAdapter.ViewHolder();
            holder.textView2=(TextView)convertView.findViewById(R.id.txt_text1);
            convertView.setTag(holder);


        }
        else {
            holder = (CustomAdapter.ViewHolder) convertView.getTag();
        }
        CustomModel classModel=mList.get(position);
        holder.textView2.setText(classModel.getName());
        holder.textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



                if(one==0)
                {
                    mSpinner.performClick();
                    one=1;

                }
                else if(one==1)
                {
                    Toast.makeText(mContext, mList.get(position).getName(), Toast.LENGTH_SHORT).show();

                    try {
                        Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
                        method.setAccessible(true);
                        method.invoke(mSpinner);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    one=0;
                }


            }
        });
        return convertView;
    }
    static class ViewHolder{

        TextView textView2;
    }
}

spinnre.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"


        android:layout_marginRight="5dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="5dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>
</LinearLayout>

customlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:layout_marginBottom="13dp"
        android:gravity="center"
        android:layout_marginTop="13dp"
        android:layout_marginLeft="5dp"
        android:paddingLeft="5dp"
        android:textColor="#000"
        />
    />
</LinearLayout>

hope it may help you.