问题
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 on a stack cards. I have one set of cards , Each cards contains some tasks. In one of my card contains one spinner.
I have successfully created the spinner and spinner items are generated from database only. The spinner items are showed without any fail.Here the spinner is to ask gender . IE male and female. my list is [MALE, FEMALE]
The spinner shows first male, then female. it is all working fine.
Here is my issue. If select female . The spinner should show that item. But is always shows male.
Below is the code
_listSpinner=(Spinner)convertView.findViewById(R.id.listSpinner);
ArrayList<HashMap<String, String>> TempOptionArrays=new ArrayList<HashMap<String, String>>();
TempOptionArrays=db.getOptins(QuestionId,taskIdBundle);
for (int i = 0; i < TempOptionArrays.size(); i++) {
SpinnerOptions.add(TempOptionArrays.get(i).get(Constants.ANSWER_SUGGESTION_TEXT_FIELD_COMMON));
}
Log.e("SpinnerOptions--",SpinnerOptions.toString());
Spinner spinner = (Spinner) convertView.findViewById(R.id.listSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, SpinnerOptions);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
Where i am doing mistake ?
Implemented listener methods
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
the listener call when the cards creates first time only. That time toast the male value . Then it is not toasted any value.
Full code
package com.panenviron.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import com.panenviron.R;
import com.panenviron.references.Constants;
import com.panenviron.userfunctions.ConnectionDetector;
import com.panenviron.userfunctions.Database;
import com.panenviron.userfunctions.UserFunctions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import link.fls.swipestack.SwipeStack;
public class TaskCardListShow extends Fragment implements SwipeStack.SwipeStackListener, View.OnClickListener {
ConnectionDetector cd;
Database db;
UserFunctions uf;
Context context;
SharedPreferences pref;
public int cardCounter;
ArrayList<HashMap<String, String>> cardList;
ArrayList<HashMap<String, String>> cardListArrayToAdapter;
ArrayList<ArrayList<HashMap<String, String>>> multiChoiceSelectedList;
ArrayList<HashMap<String, String>> tmpList = new ArrayList<HashMap<String, String>>();
private ArrayList<String> mData;
private ArrayList<String> LayOutData;
private SwipeStack mSwipeStack;
private SwipeStackAdapter mAdapter;
AutoCompleteTextView autoTextView;
int taskIdBundle;
public TaskCardListShow() {
}
public static TaskCardListShow newInstance(List<String> dataList) {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
try {
uf = new UserFunctions(getActivity());
cd = new ConnectionDetector(getActivity());
db = new Database(getActivity());
context=getActivity().getApplicationContext();
pref = getActivity().getApplicationContext().getSharedPreferences(Constants.USER_PREF, 0); // 0 - for private mode
} catch (Exception e) {
e.printStackTrace();
}
try {
Bundle bundle = this.getArguments();
if (bundle != null) {
taskIdBundle = bundle.getInt(Constants.TASK_ID_FIELD_COMMON, 0);
Toast.makeText(getActivity().getApplicationContext(),"task id --"+taskIdBundle, Toast.LENGTH_SHORT).show();
}
cardCounter=db.getNoOfCardsToDisplay(taskIdBundle);
cardList=db.getTaskQuestionsAsPerWorkId(taskIdBundle);
cardListArrayToAdapter = new ArrayList<HashMap<String, String>>();
//fillStackCard();
} catch (Exception e) {
e.printStackTrace();
}
//final RelativeLayout snackbarlocation=(RelativeLayout)view.findViewById(R.id.snackbarlocation);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);;
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar snack = Snackbar.make(view, "Do you want to close this task ?", Snackbar.LENGTH_LONG)
.setAction("Yes !.",new View.OnClickListener() {
@Override
public void onClick(View view) {
removeTaskCardFragment();
}
});
View Snackiew = snack.getView();
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)Snackiew.getLayoutParams();
params.topMargin = 100;
params.gravity = Gravity.TOP;
Snackiew.setLayoutParams(params);
snack.show();
}
});
mSwipeStack = (SwipeStack) view.findViewById(R.id.swipeStack);
mData = new ArrayList<>();
LayOutData = new ArrayList<>();
//mAdapter = new SwipeStackAdapter(mData,LayOutData);
mAdapter = new SwipeStackAdapter(cardList);
mSwipeStack.setAdapter(mAdapter);
mSwipeStack.setListener(this);
context=getActivity().getApplicationContext();
//cardCounter=10;// write function for getting card count.
return view;
}
@Override
public void onClick(View v) {
}
@Override
public void onViewSwipedToRight(int position) {
String swipedElement = mAdapter.getItem(position);
Log.e("position right-", String.valueOf(position));
}
@Override
public void onViewSwipedToLeft(int position) {
String swipedElement = mAdapter.getItem(position);
Log.e("position-", String.valueOf(position));
}
@Override
public void onStackEmpty() {
Log.e("im at empty ",tmpList.toString());
removeTaskCardFragment();
}
public void removeTaskCardFragment(){
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = manager.beginTransaction();
TaskCardListShow _TaskCardListShowFragment = new TaskCardListShow();
mFragmentTransaction.remove(_TaskCardListShowFragment);
mFragmentTransaction.commit();
manager.popBackStack();
}
public class SwipeStackAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener,AdapterView.OnItemSelectedListener {
private ArrayList<HashMap<String, String>> _taskCardDataArray;
TextView _textViewCard;
ArrayList<HashMap<String, String>> suggestionAnswer;
LinearLayout nextCardButtonLayOut;
ImageView _nextCardButton;
ArrayList<String> SpinnerOptions=new ArrayList<String>();
Spinner _listSpinner;
private RadioGroup radioGroup;
private RadioButton radioButton;
int pos;
String likertScaleText;
//private List<String> LayOutData;
DragLinearLayout dragDropAndroidLinearLayout;
public SwipeStackAdapter(ArrayList<HashMap<String, String>> taskCardDataArray) {
this._taskCardDataArray = taskCardDataArray;
//this.LayOutData = Ldata;
}
@Override
public int getCount() {
return _taskCardDataArray.size();
}
@Override
public String getItem(int position) {
return String.valueOf(_taskCardDataArray.get(position));
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
String LName=_taskCardDataArray.get(position).get(Constants.LAYOUT_NAME_FIELD_COMMON).toLowerCase();
likertScaleText="";
suggestionAnswer=new ArrayList<HashMap<String, String>>();
String QuestionText=_taskCardDataArray.get(position).get(Constants.QUESTION_TEXT_FIELD_COMMON);
if(TextUtils.isEmpty(QuestionText)){
QuestionText="Your QUESTION text will come here now it is null from api";
}
final int QuestionId= Integer.parseInt(_taskCardDataArray.get(position).get(Constants.QSTN_ID_FIELD_COMMON));
int IS_SUGGEST= Integer.parseInt(_taskCardDataArray.get(position).get(Constants.IS_SUGGEST_FIELD_COMMON));
if(IS_SUGGEST==0){
suggestionAnswer=db.getSuggestAnswerForQuestion(QuestionId,taskIdBundle);
}else{
}
try {
int id = getActivity().getApplicationContext().getResources().
getIdentifier(LName, "layout", getActivity().getPackageName());
convertView = getActivity().getLayoutInflater().inflate(id, parent, false);
tmpList = new ArrayList<HashMap<String, String>>();
switch(LName.toLowerCase()){
case "tc":
// some type of cards functionalities
break;
case "mc":
// some type of cards functionalities
break;
case "mci":
// some type of cards functionalities
break;
case "lks":
// some type of cards functionalities
break;
case "dp":
// some type of cards functionalities
break;
case "txt":
// some type of cards functionalities
break;
case "list":
_textViewCard=(TextView)convertView.findViewById(R.id.textViewCard);
_textViewCard.setText(QuestionText);
final String finalQuestionTextLIST = QuestionText;
_listSpinner=(Spinner)convertView.findViewById(R.id.listSpinner);
ArrayList<HashMap<String, String>> TempOptionArrays=new ArrayList<HashMap<String, String>>();
TempOptionArrays=db.getOptins(QuestionId,taskIdBundle);
for (int i = 0; i < TempOptionArrays.size(); i++) {
SpinnerOptions.add(TempOptionArrays.get(i).get(Constants.ANSWER_SUGGESTION_TEXT_FIELD_COMMON));
}
Log.e("SpinnerOptions--",SpinnerOptions.toString());
Spinner spinner = (Spinner) convertView.findViewById(R.id.listSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, SpinnerOptions);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
/*
// Creating adapter for spinner
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(getActivity(), android.R.layout.simple_spinner_item, SpinnerOptions);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
_listSpinner.setAdapter(dataAdapter);
//dataAdapter.notifyDataSetChanged();
_listSpinner.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();
dataAdapter.notifyDataSetChanged();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});*/
break;
case "arr":
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("position=", String.valueOf(position));
return convertView;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
回答1:
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.
回答2:
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);
来源:https://stackoverflow.com/questions/42779110/android-spinner-doesnt-showing-last-selected-item