1

I know this has been asked a million times but I was wondering if someone could point me out in the right direction.

What is the best approach to create a spinner in android and change a Listview content based on the spinner selection ? ( I basically only need to go back and forth between two listviews )

it'd be great if someone could describe the process step by step, I have no idea how to get started, I have only managed to create a listview and and an arrayadapter but I don't know how to link it to the spinner so when I select an option from the spinner the listview changes .

DavidNy
  • 61
  • 7
  • A spinner has a selection listener. That is probably the "best" way to notify that data needs changed. Please do [edit] to show what you've tried and describe the difficulty you are having with implementing that – OneCricketeer Sep 06 '16 at 06:39
  • Possible duplicate of [Android Spinner: Get the selected item change event](http://stackoverflow.com/questions/1337424/android-spinner-get-the-selected-item-change-event) – OneCricketeer Sep 06 '16 at 06:40

2 Answers2

1

For Static Data.

1.Create an ArrayList.

List lmonth=new ArrayList();

2.Populate arraylist.

lmonth.add("0");lmonth.add("1");lmonth.add("2");lmonth.add("3");lmonth.add("4");lmonth.add("5");lmonth.add("6");lmonth.add("7");lmonth.add("8");lmonth.add("9");
        lmonth.add("10");lmonth.add("11");

3.Creation of Adapter and adding list to Adapter.

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lmonth);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

4.Set Adapter to spinner.

 Spinner month=(Spinner)findViewById(R.id.spinnermonth);

month.setAdapter(dataAdapters);

This is way of populating a spinner with static data..

For Dynamic data.

1.Create an Adapter.

public class SpinnerCustomAdapter extends BaseAdapter {
    private Context mContext;
    private List<JobSearchModel> mList=new ArrayList<JobSearchModel>();
    private LayoutInflater mLayoutInflater;
    private String mType=null;


    public SpinnerCustomAdapter(Context mContext, List<JobSearchModel> list) {
        this.mContext=mContext;
        this.mList=list;

    }


    @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(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if(convertView==null){
            convertView = layoutInflater.inflate(R.layout.layout_spinner, null);
            holder = new ViewHolder();
            holder.textView2=(TextView)convertView.findViewById(R.id.txt_text2);
            convertView.setTag(holder);

        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }
        JobSearchModel classModel=mList.get(position);
        String id = mList.get(position).getId();
        if(id.equals("select")){
            holder.textView2.setTextColor(mContext.getResources().getColor(R.color.lightblack));
        }else{
            holder.textView2.setTextColor(mContext.getResources().getColor(R.color.black));
        }
        holder.textView2.setText(classModel.getDescription());
        return convertView;
    }
    static class ViewHolder{

        TextView textView2;
    }
}

The XML needed for the Adapter is

<?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_text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dami"
        android:textSize="14sp"
   android:layout_marginLeft="5dp"
        android:textColor="#4E4E4E"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"

        />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"

        />
</LinearLayout>

3.Now create a Model class according to the needs.

public class Model {
    private String id;
    private String description;
    public char[] name;

    public Model()
    {

    }
    public Model (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 getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(String.format("%02d", id)).append(" - ").append(description);
        return sb.toString();
    }

}

4.Now inside The Main class.

i)Create the Arayylist.

  private List<Model> mList = new ArrayList<Model>();

ii)Initialize and define spinner.

Spinner loc = (Spinner) findViewById(R.id.sp_loc);

iii)Set OnItemSelectedListener for Spinner.

loc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {


            }

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

            }
        });

Now populating the spinner with dynamic data. eg: code shall be given below.

private void Parsing(JsonParser jsonParser) {
    Log.i(">>>ClassResponseloc", "" + jsonParser);
    mList = new ArrayList<Model>();
    Model classModel = null;

    try {
        while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
            classModel = new JobSearchModel();
            while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
                String fieldName = jsonParser.getCurrentName();
                if ("id".equals(fieldName)) {
                    jsonParser.nextToken();
                    classModel.setId((jsonParser.getText()) + "-");
                } else if ("name".equals(fieldName)) {
                    jsonParser.nextToken();
                    classModel.setDescription(jsonParser.getText());
                }
            }

            mList.add(classModel);

        }

        SpinnerCustomAdapter adapter = new SpinnerCustomAdapter(this, mList);
        loc.setAdapter(adapter);

    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

It might help u.

Sachin Varma
  • 2,175
  • 4
  • 28
  • 39
  • not quiet sure that this is what I'm looking for so let me be a little more specific . lets say I have two listviews 1- New Cars 2- Old Cars. would I have to create two arraylists and populate each with the information I want and then create two Arrayadapters and then third step would be setting the adapters to the spinner ? – DavidNy Sep 06 '16 at 07:24
  • you have to create 2 arraylist,no need of two adpaters, u can simply use the one adapter again by changing only the arraylist name. – Sachin Varma Sep 06 '16 at 07:43
  • yes that's exactly what I need , would you mind showing an example how to use the same adapter for two arraylists ? – DavidNy Sep 10 '16 at 17:45
0
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        String selectedItem = parentView.getItemAtPosition(position);
        //based on selectedItem value decide what kind of data
        //you want to populate in your ListView and prepare adapter
        yourAdapter.notifyDataSetChanged();
    }

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

    }

});
matejko219
  • 1,601
  • 10
  • 14