Join FlipAndroid.COM Telegram Group: https://t.me/joinchat/F_aqThGkhwcLzmI49vKAiw


(Dinámico) Hiladores múltiples estado / ciudad

Tengo que desarrollar una vista de androide tal que tengo 2 controles del hilandero en él, uno para el estado y el segundo para las ciudades.

Mi pregunta es, ¿cómo puedo poblar la ciudad spinner automáticamente cada vez que un estado está seleccionado?

¿Cuál es la lógica detrás de esto?

Mi string.xml:

<?xml version="1.0" encoding="utf-8"?> <resources> <string name="spinner_category"></string> <string-array name="category_state"> <item >kerala</item> <item >tamil nadu</item> <item >Andra Pradesh</item> <item >karnataka</item> </string-array> </resources> 

Mi main.xml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dip" android:text="Select : "/> <Spinner android:layout_width="250dip" android:layout_height="wrap_content" android:id="@+id/spinner_state"/> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dip" android:text="Select : "/> <Spinner android:layout_width="250dip" android:layout_height="wrap_content" android:id="@+id/spinner_state"/> </LinearLayout> </LinearLayout> 

Y mi archivo activity.java:

 package com.converter; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class ConverterActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner spinner_s = (Spinner)findViewById(R.id.spinner_state); ArrayAdapter<CharSequence> category_adapter = ArrayAdapter.createFromResource( this, R.array.category_array, android.R.layout.simple_spinner_item); category_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_s.setAdapter(category_adapter); } } 

4 Solutions collect form web for “(Dinámico) Hiladores múltiples estado / ciudad”

Ejemplo:

  Spinner city=(Spinner)findViewById(R.id.citySpinner); Spinner state=(Spinner)findViewById(R.id.stateSpinner); final ArrayList<String> state_options=new ArrayList<String>(); final ArrayList<String> city_options=new ArrayList<String>(); state_options.add("state_1"); state_options.add("state_2"); state_options.add("state_3"); // Here you can also get a cursor and add Strings as options to state_options instead of what i have done city_options.add("city_1_state_1"); city_options.add("city_2_state_1"); city_options.add("city_3_state_1"); // Here you can also get a cursor and add Strings as options to city_options instead of what i have done ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,city_options); city.setAdapter(cityAdapter); ArrayAdapter<String> stateAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,state_options); state.setAdapter(stateAdapter); state.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) { String stateName=state_options.get(position).toString(); resetCity(stateName); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); 

Ahora,

 public void resetCity(String stateName) { city_options.removeAll(city_options);//i haven't checked this. if(stateName.eqauls("state_1")) { city_option.add("city_1_state_1"); city_options.add("city_2_state_1"); city_options.add("city_3_state_1"); //you can also get a cursor and add Strings as options to city_options instead of what i have done } else if(stateName.eqauls("state_2")) { city_option.add("city_1_state_2"); city_options.add("city_2_state_2"); city_options.add("city_3_state_2"); // you can also get a cursor and add Strings as options to city_options instead of what i have done } else { city_option.add("city_1_state_3"); city_options.add("city_2_state_3"); city_options.add("city_3_state_3"); //you can also get a cursor and add Strings as options to city_options instead of what i have done } ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,city_options); city.setAdapter(cityAdapter); } 

Este es el city_options más sencillo. Puede establecer sus city_options y state_options desde su base de datos. Y luego puede usarlo para poblar los spinners accoring.

Aquí está la manera correcta querida ….

Yo había escrito todos los estados y ciudades necesarias en string_arays ….

me gusta

 <string-array name="State_array"> <item >s1</item> <item >s2</item> <item >s3</item> <item >s4</item> </string-array> //then cities array for each states, like <string-array name="State1Cities_array"> <item >c11</item> <item >c12</item> <item >c15</item> <item >c13</item> </string-array> <string-array name="State2Cities_array"> <item >c1</item> <item >c2</item> <item >c5</item> <item >c3</item> </string-array> // and so on for all the states 

Luego en xml principal agregó 2 hilanderos para ambos. I belive todo u puede hacer yo simple, na?

Entonces tengo mi main.xml como …

 spinner_states_activity = (Spinner)findViewById(R.id.spinner_states_main); spinner_states_activity.setOnItemSelectedListener(this); adapter = ArrayAdapter.createFromResource( this, R.array.state_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(R.layout.myspinner); // my layout for spinners u can use urs or defalut. k? spinner_states_activity.setAdapter(adapter); spinner_cities_activity = (Spinner)findViewById(R.id.spinner_cities_main); spinner_cities_activity.setOnItemSelectedListener(this); //and in function onItemSelected int pos,pos2; pos = spinner_states_activity.getSelectedItemPosition(); int iden=parent.getId(); if(iden==R.id.spinner_states_main) { pos2 = 0; switch (pos) { case 0: unit_adapter= ArrayAdapter.createFromResource( this, R.array.States1Cities_array, android.R.layout.simple_spinner_item); break; case 1: unit_adapter= ArrayAdapter.createFromResource( this, R.array.States3Cities_array, android.R.layout.simple_spinner_item); break; // all the StatesxCities entires.... default: break; } spinner_cities_activity.setAdapter(unit_adapter); unit_adapter.setDropDownViewResource(R.layout.myspinner); } 

Sólo echa un vistazo y hazlo por ti mismo … Espero que esto ayude ua poco …

K queridos amigos .. Sujith

 public class ConverterActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner citySpinner = (Spinner)findViewById(R.id.spinner_city); final ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]); // starts empty city_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_city.setAdapter(city_adapter); Spinner categorySpinner = (Spinner)findViewById(R.id.spinner_state); final ArrayAdapter<String> categoryAdapter = ArrayAdapter.createFromResource( this, R.array.category_array, android.R.layout.simple_spinner_item); categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorySpinner.setAdapter(category_adapter); categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selectedState = parent.getItemAtPosition(position); cityAdapter.clear(); // remove previous entries // look up your cities for the state selectedState, using your own method cityAdapter.add(the cities you want); // do that in a loop for all your cities cityAdapter.notifyDataSetChanged(); }; @Override public void onNothingSelected(AdapterView<?> parent) { // do nothing } }); } } 

Nota: codificado en el editor StackOverflow, puede haber algunos errores de sintaxis 🙂

Para buscar las ciudades de cada estado, utilice cualquier método que desee: puede definirlas en varios recursos de conjuntos de cadenas o obtenerlos de una base de datos, etc.

Tienes que hacer el siguiente paso

  1. Crear fuente de datos de ciudades (ya sea base de datos o en hashmap ("estado", "ciudad")).

  2. Set setOnItemSelectedListener (oyente) a spinner que contiene estados.

  3. OnItemSelected () método del listner anterior buscar los datos de dataouce creado en el primer paso y adjuntarlo a la ciudad spinner.

Eso es.

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.