I'm a newbie in Android Development and I want to implement Spinner
. My problem is that I have an array which has 9 values for a key Category. My array looks like:
MyArray
[{Category=Things To Do},
{Category=Transportation},
{Category=Food and Drink},
{Category=Accommodation},
{Category=Shopping},
{Category=Money and Costs},
{Category=Business},
{Category=Turkey Tour},
{Category=Events}]
I want to get value of category key. i need MyArray for spinner as bellow:
MyArray
{
Things To Do
Transportation
Food and Drink
Accommodation
Shopping
......
}
It is similar to iPhone code.
// iPhone code
for(int i=0; i<[arrayCategory count]; i++)
{
NSString *strSubTitle=[[arrayCategory objectAtIndex:i]objectForKey:@"category"];
}
Any idea?
Please help me.
Thanks
first create a xml in string for your String array
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="planet_prompt">Choose a planet</string>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
then use the above xml for string array in your code like below
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
try this way, it will work fine.
public class ArrayAdapterDemo2 extends Activity implements
AdapterView.OnItemSelectedListener {
TextView selection;
String[] category= { "football","cricket" ,"baseball"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection = (TextView) findViewById(R.id.selection);
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, category);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
selection.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With