I'm using Two Spinners where Second Spinner Value is based on First Spinner Value.
For Example If user Select Option A in First Spinner Then Second Spinner drop down list must contain value ( ox, cow, goat ) and if user select option B, then second Spinner value must contain ( Lion, Tiger and Cheetha ).
But I'm unable to do so. On selecting any value in first spinner value, Second Spinner always loads same value. Below is the screenshot
As you can see, In selecting any option in first spinner master or diploma...In second spinner value is same.it does not change.
Below is my Activity Code
public class UploadBook extends AppCompatActivity
Spinner spinnerCountry,spinnerDivision,spinner_condition;
ArrayAdapter<String> countryArray,divisionArray;
String item = "start";
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_book);
getSupportActionBar().setTitle("Upload book");
spinnerCountry = (Spinner) findViewById(R.id.spinnerCountry);
//implementing OnItemSelectedListener (need to override the method)
spinnerCountry.setOnItemSelectedListener(this);
countryArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
countryArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryArray);
countryArray.add("Master");
countryArray.add("Diploma");
countryArray.setNotifyOnChange(true);
spinnerCountry.setSelection(0);
spinnerDivision = (Spinner) findViewById(R.id.spinnerDivision);
//implementing OnItemSelectedListener (need to override the method)
spinnerDivision.setOnItemSelectedListener(this);
divisionArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
divisionArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDivision.setAdapter(divisionArray);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
count = position;
//first spinner item position
int countrySpinnerPosition = spinnerCountry.getSelectedItemPosition();
switch (countrySpinnerPosition){
case 1:
//fill data for second spinner
fillMasterDivision();
break;
case 2:
//fill data for second spinner
fillDiplomaDivision();
break;
}
}
private void fillMasterDivision() {
divisionArray.clear();
divisionArray.add("Select Subject:-");
divisionArray.add("MSC Physics");
divisionArray.add("MSC Chemistry");
divisionArray.notifyDataSetChanged();
}
private void fillDiplomaDivision() {
divisionArray.add("Select Subject:-");
divisionArray.add("Science");
divisionArray.add("CTEVT");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Please Help.
There is two mistake in your code.
CountrySpinnerPosition will be 0 and 1 for your case so the case should be "case 0" and "case 1".
In fillDiplomaDivision method, you have to first clear the list and after adding into the list you have to call notifyDataSetChanged().
try to clear the arraylist and notifydatasetchanged in second method too
private void fillDiplomaDivision() {
divisionArray.clear();
divisionArray.add("Select Subject:-");
divisionArray.add("Science");
divisionArray.add("CTEVT");
divisionArray.notifyDataSetChanged();
}
First of all ,you are using same onItemSelected for both the spinner . so remove spinnerCountry.setOnItemSelectedListener(this); and spinnerDivision.setOnItemSelectedListener(this);
After setting data to spinnerCountry use this .
spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i == 0){
fillMasterDivision();
}else{
fillBachelorDivision();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
and clear your Division array in fillBachelorDivision()
See my example:
I have 2 spinners, firstSpinner and secndSpinner, Second depends of First.
First you have to initialize the spinners in onCreate method, and follow steps:
1 - You'll insert in first spinner your data ("Master", "Diploma");
2 - You'll create a function that will update the second spinner with associated values.
firstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
createSecondSpinnerByFirst(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
});
private void createSecondSpinnerByFirst(Integer position) {
List<String> secValues = new ArrayList<>();
switch (position) {
case 1:
// insert in secValues array the strings of this condition
break;
case 2:
// insert in secValues array the strings of this condition
break;
}
// usually I use Adapter
final SpinnerAdapter adapter = new SpinnerAdapter(this, secValues);
secndSpinner.setAdapter(adapter);
}
//Code of myAdapter
public class SpinnerAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> mValues;
public SpinnerAdapter(Context ctx, List<String> values) {
super(ctx, 0, values);
context = ctx;
mValues = values;
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Process getItem(int position) {
return mValues.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return returnLayoutSpinner(context, convertView, mValues.get(position));
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return returnLayoutSpinner(context, convertView, mValues.get(position));
}
}
//My function to return the adapter view
private View returnLayoutSpinner(Context context, View convertView, String value) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(
R.layout.spinner_items_view, null);
}
TextView txt = convertView.findViewById(R.id.txtSpinnerItem);
txt.setText(value, 25);
return convertView;
}
//spinner_items_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/txtSpinnerItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|left"
android:padding="13dp"
android:textColor="#android:color/black"
android:textSize="16sp">
</TextView>
private void fillDiplomaDivision() {
//add this line in your code and it solve
divisionArray.clear();
divisionArray.add("Select Subject:-");
divisionArray.add("Science");
divisionArray.add("CTEVT");
}
Related
Been making my first app and slow progress is being made. Just wondering how I return a Spinner value to pass it as a string.
Here is my code:
First the event class:
public void event(){
calanderBtn = (Button)findViewById(R.id.eventBtn);
calanderBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(CalendarContract.Events.TITLE, "Home");
intent.putExtra(CalendarContract.Events.DESCRIPTION, "Cleaning : ");
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, "Home");
startActivity(intent);
}
});
}
Second the Spinner Class:
public void selectcleaning() {
spCleaning = (Spinner) findViewById(spinner);
adapterCleaningType = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cleaningType);
adapterCleaningType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCleaning.setAdapter(adapterCleaningType);
}
I'm trying to select the value from selectcleaning (Value is either Yes or No) and pass it in the descrption in the Calendar of the event class and I'm not sure what to do.
you can use this code to get the value
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
or get the value when spinner selected using OnItemSelectedListener (Android Doc)
public class SpinnerActivity extends Activity implements
OnItemSelectedListener {
#Override
protected void onStart() {
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
You should try using the Overrides for the spinner class as so:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}});
For your purposes 'int position' would equal 0 (yes) or 1 (no)
Try setting an on item selected listener. When an item is selected, you can store that value in a global variable. It gets the first item by default too.
spCleaning.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Value is current spinner item
globalStringVariable = (String) parent.getItemAtPosition(position);
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
// This is default, before you've selected anything.
// It gets the first value.
globalStringVariable = parent.getItemAtPositon(0);
}
});
I don't know if I did any mistake while rotating the list or something else needs to be done..I would appreciate it very much if anyone could help me on figuring out the solution.
I have a vertical ListView with 5 items(in the left side of the screen-shots) as shown in the screen-shots:
As you can see the list should be rotated each time an item is clicked or selected.The problem is that the code that i have implemented works with onItemClickListener(when the item clicked is one position below or above the item in the middle),but it doesn't work with onItemSelectedListener(the list rotates for two times (for a single direction) then stops rotating in that direction, meaning onItemSelected is not called at all).
May be more screen shots will make it clear:
Well this might make you more confused though.. I want a list whose selected item takes the middle (Text Color Blue) position and the list rotates accordingly.
Please Help.... Thanks a Lot.
Source Code: Main Activity:
public class MainActivity extends AppCompatActivity {
private ListView categoryList;
ListCustomAdapter listadapter;
private List<TextItem> txtItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categoryList = (ListView) findViewById(R.id.listCategories);
listadapter=new ListCustomAdapter(this,txtItems);
categoryList.setAdapter(listadapter);
categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listadapter.getPosition(i);
Log.d("position",""+i);
if(i>2) {
Log.d("position1",""+(i-1));
Collections.rotate(txtItems, 4);
listadapter.notifyDataSetChanged();
}else if(i<2){
Log.d("position2",""+(1-i));
Collections.rotate( txtItems,1);
listadapter.notifyDataSetChanged();
}
else{
}
}
});
categoryList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("inside" ,"onItemSelected");
if(i>2) {
Collections.rotate(txtItems,4);
Log.d("position rotated",""+i);
listadapter.notifyDataSetChanged();
}else if(i<2){
Collections.rotate( txtItems,1);
listadapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Log.e("inside" ,"onNothingSelected");
}
});
}
ListCustomAdapter:
public class ListCustomAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<TextItem> txtItems;
int pos;
public ListCustomAdapter(Activity activity, List<TextItem> txtItems) {
this.activity = activity;
this.txtItems = txtItems;
}
#Override
public int getCount() {
return txtItems.size();
}
#Override
public Object getItem(int location) {
return txtItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.vertical_list_item, null);
holder = new ViewHolder();
holder.category = (TextView) convertView.findViewById(R.id.category_name);
holder.listLayout= (LinearLayout) convertView.findViewById(R.id.list_layout);
convertView.setTag(holder);
}else
{
holder = (ViewHolder) convertView.getTag();
}
if (pos == position) {
Log.d("translated","done of position"+pos);
holder.category.setTranslationX(10.17f);
} else {
/* view.imgViewFlag.getLayoutParams().height = 140;
view.imgViewFlag.getLayoutParams().width = 300;*/
holder.category.setTranslationX(1.0f);
Log.d("translated","default of position"+pos);
// view.imgViewFlag.setBackgroundResource(0);
holder.category.setBackgroundResource(0);
}
TextItem model = txtItems.get(position);
holder.category.setText(model.getTitleName());
if(position==2)
holder.category.setTextColor(Color.BLUE);
/*
creating objects to access the views
*/
return convertView;
}
public void getPosition(int position) {
this.pos = position;
}
static class ViewHolder {
TextView category;
LinearLayout listLayout;
}
}
Since my code works fine for OnItemClickListener, I figured out that the item that's clicked is set as selected in the list..so for OnItemSelectedListener... I had to make the middle position as selected all the time .. Hence,I added the following
categoryList.setSelection(2); /*2 is the mid position for the list with 5 items *\
after the list was rotated i.e:
categoryList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("inside" ,"onItemSelected");
if(i>2) {
Collections.rotate(txtItems,4);
categoryList.setSelection(2);
Log.d("position rotated",""+i);
listadapter.notifyDataSetChanged();
}else if(i<2){
Collections.rotate( txtItems,1);
categoryList.setSelection(2);
listadapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Log.e("inside" ,"onNothingSelected");
}
});
How to hide an item from other spinners that is currently selected in one spinner?
I've tried removing the items via ArrayList of strings and ArrayAdapters, but I've noticed as soon as it's removed from the list, the selection is no longer referenced to the list item (because it does not exist anymore).
Now suppose, I have 4 spinner that are created dynamically and they all have the same ArrayList as their resource and now i would like to use this adapter to fetch the position of the selected item from 1 spinner and then hide it from 3 other spinners.
for (int i = 0; i < numberOfStops; i++) {
AddStopView stopView = new AddStopView(getActivity());
stopView.setCallback(BaseBookingFragment.this);
stopView.setPassengerNames(extraPassengerNames);
stopViews.add(stopView);
parent.addView(stopView, viewPosition);
}
In above code i am creating Stop Views dynamically and each Stop View having Passenger Name spinner. And these all spinners have the same ArrayList as their resource.
piece of code from AddStopView.java
public AddStopView(Context context) {
super(context);
initialize();
}
public void setCallback(StopViewCallback callback) {
this.callback = callback;
}
public void setPassengerNames(List<String> passengerNames) {
this.passengerNames = passengerNames;
passengerAdapter.setNames(passengerNames);
}
private void initialize() {
inflate(getContext(), R.layout.view_stop, this);
passengerAdapter = new ExtraPassengerAdapter(getContext());
passengerAdapter.setNames(passengerNames);
nameSpinner.setAdapter(passengerAdapter);
nameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (view == null) {
return;
}
passengerName = (String) view.getTag();
if (position != 0)
callback.updatePassengerList(AddStopView.this, (position - 1));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
code of call back of nameSpinner.setOnItemSelectedListener
#Override
public void updatePassengerList(AddStopView addStopView, int position) {
for (String passName : extraPassengerNames) {
if (addStopView.getPassengerName().equals(passName)) {
extraPassengerNames.remove(passName);
break;
}
}
for (AddStopView stopView : stopViews) {
if (!stopView.equals(addStopView))
stopView.setPassengerNames(extraPassengerNames);
}
}
code from ExtraPassengerAdapter.java
public class ExtraPassengerAdapter extends BaseAdapter {
private List<String> names = new ArrayList<>();
private Context context;
public ExtraPassengerAdapter(Context context) {
this.context = context;
names.add(get0Position());
}
public void setNames(List<String> names) {
this.names.clear();
this.names.add(get0Position());
this.names.addAll(names);
notifyDataSetChanged();
}
#Override
public int getCount() {
return names.size();
}
#Override
public String getItem(int position) {
return names.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_stop, parent, false);
String name = getItem(position);
textView.setText(name);
textView.setTag(name);
return textView;
}
private String get0Position() {
return context.getString(R.string.passenger_name);
}
}
I think the right way to solve you problem is to create one list with all possible options and 4 lists with 4 adapters for each spinner. When something selected you update each list according to logic you described and call adapter.notifyDataSetChanged() for each adapter.
I'm trying retrieve an object from my spinner array and set it to a certain constant, in this case "EFFECT_AQUA"
My array
String[] spinnerValues = {"Aqua", "Mono", "Blackbird", "Negative"};
when the user clicks on the "Aqua" in the spinner I want the screen to change to Aqua.
My spinner is set and called
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this,R.layout.custom_spinner,spinnerValues));
But not sure how should I approach. Seen many different answers but haven't found anything working.
I know my switch will come in this part
class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
}
Any help is appricated!!
If you want to retrieve an object from your spinner array on item click, you can easily do it with the position parameter in the method onItemSelected.
For example :-
class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String itemSelected = spinnerValues[position];
//Set this to a constant
}
}
Now if you select Aqua, then code will set the variable itemSelected to Aqua.
I hope this is what you need
final Spinner cardStatusSpinner1 = (Spinner)findViewById(R.id.text_interested);
String cardStatusString;
cardStatusSpinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
cardStatusString = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
put the code below to get the item first then you can manipulate by taking the values like aqua or any color.
spinner = (Spinner)findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,spinnerValues));
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
TextView tv = (TextView)view;
Toast.makeText(getApplicationContext(), tv.getText().toString(), 5000).show();
switch(tv.getText().toString()){
case "Aqua":{
//change the color to aqua
break;
}
case " ...":{
//
break;
}
//.... for all the option
}
}
I have two spinners on my layout as below:
public class DemoActivity extends Activity {
private static final String STATE_SCALE = "state-scale";
private static final String STATE_CENTER_X = "state-center-x";
private static final String STATE_CENTER_Y = "state-center-y";
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
String text1 = spinner1.getSelectedItem().toString();
Spinner spinner3 = (Spinner) findViewById(R.id.spinner3);
String text3 = spinner3.getSelectedItem().toString();
if (text1.equals("Harris Academy"))
Harris(spinner1);
if (text1.equals("Harris Academy") && text3.equals("Ground Floor")) {
Toast.makeText(getBaseContext(), text3, Toast.LENGTH_LONG).show();
try {
SubsamplingScaleImageView imageView =
(SubsamplingScaleImageView) findViewById(id.imageView);
imageView.setImageAsset("DSC00277.png");
if (savedInstanceState != null &&
savedInstanceState.containsKey(STATE_SCALE) &&
savedInstanceState.containsKey(STATE_CENTER_X) &&
savedInstanceState.containsKey(STATE_CENTER_Y)) {
imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE),
new PointF(savedInstanceState.getFloat(STATE_CENTER_X),
savedInstanceState.getFloat(STATE_CENTER_Y)));
}
} catch (IOException e) {
Log.e(DemoActivity.class.getSimpleName(), "Could not load asset", e);
}
}
}
}
This works fine when the app starts it gets the value of spinner 1 and spinner 3 and then does something depending on the values.
How do I extend it so that when I select an item on either spinner it does something based on the new values?
To get updated value as user select item from spinner,
You have to implement spinner's onItemSelectedListner
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Do your stuff here for spinner1
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Do your stuff here for spinner3
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
If you want to manipulate views or data on the selection of item in Spinner you need to implement
ItemSelectedListener to the particular Spinner.
Sample Code:
// in onCreate() or where you want to bind this Views with XML views
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner3 = (Spinner) findViewById(R.id.spinner3);
// mItemSelectedListener Object of OnItemSelectedListener to handle Item Selection to Spinners.
spinner1.setOnItemSelectedListener(mItemSelectedListener);
spinner3.setOnItemSelectedListener(mItemSelectedListener);
}
// Creating an Object of Anonymous Class so no need to create another instance for same class
// OutSide of onCreate() method.
OnItemSelectedListener mItemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (view.getId()) {
case R.id.spinner1:
// Manipulates Views at selection of item in Spinner1
break;
case R.id.spinner3:
// Manipulates Views at selection of item in Spinner3
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};