ANDROID spinner doesn't showing last selected item

后端 未结 2 1369
别跟我提以往
别跟我提以往 2020-12-21 15:07

But i am not able to find the solution for this. I know this may be asked before. But it is really different from other issues.

I am trying to implement one spinner

相关标签:
2条回答
  • 2020-12-21 15:45

    Actually you are assigning same id for two different variable

     _listSpinner=(Spinner)convertView.findViewById(R.id.listSpinner);
    

    and

    Spinner spinner = (Spinner) convertView.findViewById(R.id.listSpinner);
    

    and also creating 2 different adapter for same spinner please avoid duplicate it solve yous problem.

    0 讨论(0)
  • 2020-12-21 16:03

    Create a custom layout for your spinner item...

    spinner_item.xml

    <?xml version="1.0" encoding="utf-8"?>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:textColor="#000000" >
    

    Now use it in your adapter:

        Spinner spinner = (Spinner) convertView.findViewById(R.id.listSpinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, SpinnerOptions);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner.setAdapter(adapter);
        //adapter.notifyDataSetChanged();
        spinner.setOnItemSelectedListener(this);
    

    Second way

    force the spinner to setselection using spinner.setSelection()

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                Toast.makeText(parentView.getContext(), "Selected ---: " + SpinnerOptions.get(position), Toast.LENGTH_LONG).show();
    
                if (position == 0) {
                    spinner.setSelection(((ArrayAdapter<String>) spinner.getAdapter()).getPosition("Male"));
                } else {
                    spinner.setSelection(((ArrayAdapter<String>) spinner.getAdapter()).getPosition("Female"));
                }
    
            }
    
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                Log.d("Log", "Called");
                spinner.setSelection(((ArrayAdapter<String>) spinner.getAdapter()).getPosition("Female"));
            }
        });
    

    in this case you don't need spinner.setOnItemSelectedListener(this);

    0 讨论(0)
提交回复
热议问题