This must be a simple problem that i might again overlooked. Here is my problem I have a string array on my string.xml
<string-array name="country_array">
<item>Alabama</item>
<item>Florida</item>
<item>Los Angeles</item>
<item>Virginia</item>
<item>California</item>
<item>Texas</item>
<item>Hawaii</item>
<item>Miami</item>
<item>New Jersey</item>
<item>Boston</item>
<item>Philadelphia</item>
<item>VaChina</item>
</string-array>
So now I am calling in on my main activity and placed it on my spinner
selectedCountry = (EditText) findViewById(R.id.etCity);
//get the spinner from resource
Spinner spinner = (Spinner) findViewById(R.id.spinnerCountry);
//then defining ArrayAdapter using country_array
ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(this, R.array.country_array,
android.R.layout.simple_spinner_item);
//set the appearance of widget items that show when open the widget
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//set the adapter to spinner
spinner.setAdapter(adapter);
//set the action listener
spinner.setOnItemSelectedListener(listener);
Now on my onclicklistener of my spinner this is my code
View.OnClickListener selectCountry = new View.OnClickListener() {
public void onClick(View v) {
Spinner spinner = (Spinner) findViewById(R.id.spinnerCountry);
spinner.performClick();
}
};
private OnItemSelectedListener listener =new OnItemSelectedListener() {
//do what ever you want to do when item selected
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
//i get the item using selected item position and set it into selectedCountry
selectedCountry.setText(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
}
};
Every thing works fine until I figured out that on my selectedCountry text is the first item on my array. Is there anyway that I could add a default value on my edittext?
Please add "Select Country" in your String array as first item.
Like
<string-array name="country_array">
<item>Select Country</item>
<item>Alabama</item>
<item>Florida</item>
<item>Los Angeles</item>
<item>Virginia</item>
<item>California</item>
<item>Texas</item>
<item>Hawaii</item>
<item>Miami</item>
<item>New Jersey</item>
<item>Boston</item>
<item>Philadelphia</item>
<item>VaChina</item>
</string-array>
then
add below code in onItemSelected()
public void onItemSelected(AdapterView<?> adapterView, View view,int position, long arg3)
{
if(!spinner.getSelectedItem().toString().equalsIgnoreCase("Select Country"))
{
selectedCountry.setText(spinner.getSelectedItem().toString());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.