Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"
android:entries="#array/num"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn"
android:text="Click ME"
android:gravity="center"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txtv"
/>
</LinearLayout>
Spin.java
package com.and.spin;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class spin extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv=(TextView)findViewById(R.id.txtv);
Button b=(Button)findViewById(R.id.btn);
final Spinner s=(Spinner)findViewById(R.id.spin);
b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String spin=s.toString();
tv.setText(spin);
}
});
}
}
In this program, i'm trying to display selected options from the Spinner to the TextView. But output dsiplays android.widget.Spinner#44c0d7f8
I want output like (1,2,3,4 or 5) as the option selected in Spinner rather than android.widget.Spinner#44c0d7f8
You dont need shared preference to load values in spinner. You just need to declare array in string.xml file and load that.I am giving you my code.Just use it.:-
STEP-1:-
Declare array for spinner in your string.xml(res->values->strings.xml):--
<string-array name="country_array">
<item>Greece</item>
<item>United Kingdom</item>
<item>Italy</item>
<item>France</item>
<item>Germany</item>
<item>Turkey</item>
<item>Poland</item>
<item>India</item>
</string-array>
STEP-2:-
Declare Spinner widget in your layout xml file
<Spinner
android:id="#+id/spinCountry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:paddingLeft="8dp"
android:popupBackground="#android:color/white"
android:scrollbars="none"
android:spinnerMode="dropdown" />
STEP-3:-
Declare Spinner in your Activity
Spinner spinCountry;
spinCountry= (Spinner) findViewById(R.id.spinCountry);//fetch the spinner from layout file
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.country_array));//setting the country_array to spinner
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCountry.setAdapter(adapter);
//if you want to set any action you can do in this listener
spinCountry.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
b.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
String spin=s.getSelectedItem().toString();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tv.setText(spin);
}
});
spinCountry.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
try {
String select_item =parentView.getItemAtPosition(position).toString();
}
catch (Exception e) {
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
You are calling toString() method on spinner to get the selection which is wrong. You need to call getSelectedItemPosition() method to get the selection.
Related
I am getting values from json string and add it in arraylist getSpinArrList.I have posted the relevant code.
My issue is, Spinner not showing the first item and OnItemClick is not working in spinner.
But If I click spinner, I can view only the items I am getting from arraylist.
MainActivity.java:
Spinner spinCrePage;
spinCrePage = (Spinner) findViewById(R.id.sp_create_page);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, getSpinArrList);
adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCrePage.setAdapter(adapter_state);
spinCrePage.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getApplicationContext(),"Working" , Toast.LENGTH_SHORT).show();
spinCrePage.setSelection(position);
String selState = (String) spinCrePage.getSelectedItem();
// textView.setText("Selected Android OS:" + selState);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
onItemSelected, you have to create a switch case using the position. For every position create a case and implement it with ur desiered code...
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
Toast.makeText(getApplicationContext(),"Working" , Toast.LENGTH_SHORT).show();
break;
case 1:
//code
break;
}
}
please Use this code and Follow these steps
List of Items in Spinner
Open “res/values/strings.xml” file, define the list of items that will display in Spinner (dropdown list).
File : res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyAndroidApp</string>
<string name="country_prompt">Choose a country</string>
<string-array name="country_arrays">
<item>Malaysia</item>
<item>United States</item>
<item>Indonesia</item>
<item>France</item>
<item>Italy</item>
<item>Singapore</item>
<item>New Zealand</item>
<item>India</item>
</string-array>
Create a xml file res/layout/main.xml
use country_arrays in Spinner entries
<?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" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
Code
Create Java file MyAndroidAppActivity.java
package com.webastral.drinkin.home;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(
MyAndroidAppActivity.this,
"OnClickListener : " + "\nSpinner 1 : "
+ String.valueOf(spinner1.getSelectedItem())
+ "\nSpinner 2 : "
+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
Create Java File CustomOnItemSelectedListener.java
package com.webastral.drinkin.home;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(
parent.getContext(),
"OnItemSelectedListener : "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Hope This wil Help you
In your application, i think the only time when the toast doesn't appear is when you are selecting the same item twice consecutively. I tried out your code and it works fine for me. You might want to remove the
spinCrePage.setSelection(position);
from your code. It doesn't have any use at all.
The OnItemSelected() will be triggered only when you select a different item from the previous item in the Spinner.
And as far as the problem of "Spinner not showing the first item", you should probably check the contents of your arraylist. See if anything is getting removed during execution or something. Check loops with which you are adding data into arraylist.
"OnClick not working" : I am pretty sure that the Spinner doesn't have an OnClickListener, Spinners uses OnItemSelectedListener().
I am trying to set reminders. There is a spinner with 5 values (1,2,3,4,5). Let's say if user selects 3 from the spinner there should be 3 "Add Time" buttons displayed. Similarly if user selects 5, five "Add Time" button should be displayed.
User presses "Add Time" button and time picker will be displayed to select time for the reminders. I've created spinner through xml from res/string folder and set an array of 5 item (1,2,3,4,5). I don't know to display these "Add Time" buttons as per the selection of value from the spinner.
Would greatly appreciate any suggestions/guidance.
Thanks a lot...
package com.example.medicationreminder;
import jim.h.common.android.lib.zxing.config.ZXingLibConfig;
import jim.h.common.android.lib.zxing.integrator.IntentIntegrator;
import jim.h.common.android.lib.zxing.integrator.IntentResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
import com.example.medicationreminder.InteractiveArrayAdapter.ViewHolder;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
public class MedInfo extends Activity implements OnClickListener{
private Button daily, weekly, mScanBarcode;
private Handler handler = new Handler();
private ZXingLibConfig zxingLibConfig;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_med_info);
mScanBarcode = (Button) findViewById(R.id.Barcodescanner);
mScanBarcode.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.med_info, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == mScanBarcode)//When scan barcode button is clicked
{
IntentIntegrator.initiateScan(MedInfo.this, zxingLibConfig);//Intent that opens camera for scanning through zxing Library
}
/* else if(v == weekly)
{
Intent weekly = new Intent(MedInfo.this,Weekly.class);
startActivity(weekly);
} */
else if(v == daily)
{
Intent daily = new Intent(MedInfo.this, DailyMed.class);
startActivity(daily);
}
}
//The method that cathes the result after scanning is done
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case IntentIntegrator.REQUEST_CODE:
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode,
resultCode, data);
if (scanResult == null)
{
return;
}
final String result = scanResult.getContents();//scanned result
if (result != null)
{
handler.post(new Runnable()
{
#Override
public void run()
{
showScannedResult(result);//opening pop up showing scanned result
}
});
}
break;
default:
}
}
//Pop up dialog showing scanned result
private void showScannedResult(String result)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scanned Result")
.setMessage(result)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
//Array list for selection of Days
public class Weekly extends ListActivity {
public void onCreate1(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
setListAdapter(adapter);
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
list.add(get("Monday"));
list.add(get("Tuesday"));
list.add(get("Wednesday"));
list.add(get("Thursday"));
list.add(get("Friday"));
list.add(get("Saturday"));
list.add(get("Sunday"));
// Initially select one of the items
list.get(1).setSelected(true);
return list;
}
private Model get(String s) {
return new Model(s);
}
// Spinner item selection and add button
public class spinning extends Activity implements AdapterView.OnItemSelectedListener{
LinearLayout list;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceSate) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceSate);
setContentView(R.layout.activity_med_info);
spinner = (Spinner)findViewById(R.id.spinner1);
list = (LinearLayout)findViewById(R.id.list);
ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter.createFromResource(this,
R.array.dose_arrays, android.R.layout.simple_spinner_item);
adapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterSpinner);
spinner.setOnItemSelectedListener(this);
}
public void addButton(int number){
list.removeAllViews();
for(int i = 0; i<number;i++){
Button button = new Button(getApplicationContext());
button.setText("Add Time");
list.addView(button);
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i,
long l) {
// TODO Auto-generated method stub
switch(i){
case 0:
addButton(1);
break;
case 1:
addButton(2);
break;
case 2:
addButton(3);
break;
case 3:
addButton(4);
break;
case 4:
addButton(5);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
}
Medinfo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/android"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MedInfo" >
<EditText
android:id="#+id/MedName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_alignTop="#+id/radioGroup1"
android:ems="10"
android:hint="Name of Medicine" >
<requestFocus />
</EditText>
<Button
android:id="#+id/Barcodescanner"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/MedName"
android:layout_below="#+id/MedName"
android:layout_marginTop="14dp"
android:text="Scan Barcode" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Barcodescanner"
android:layout_below="#+id/Barcodescanner"
android:layout_marginTop="44dp"
android:text="Dose per day"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:entries="#array/dose_arrays"
android:prompt="#string/dose_prompt" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner" android:id="#+id/list">
</LinearLayout>
<CheckBox
android:id="#+id/checkMon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="114dp"
android:text="Mon" />
<CheckBox
android:id="#+id/checkTue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkMon"
android:layout_alignBottom="#+id/checkMon"
android:layout_toRightOf="#+id/AddTime"
android:text="Tue" />
<CheckBox
android:id="#+id/checkWed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkTue"
android:layout_alignBottom="#+id/checkTue"
android:layout_centerHorizontal="true"
android:text="Wed" />
<CheckBox
android:id="#+id/checkThur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/checkWed"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#+id/checkWed"
android:text="Thur" />
<CheckBox
android:id="#+id/checkFri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/checkTue"
android:layout_marginTop="27dp"
android:layout_toRightOf="#+id/radioGroup1"
android:text="Fri" />
<CheckBox
android:id="#+id/checkSat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkFri"
android:layout_alignBottom="#+id/checkFri"
android:layout_alignLeft="#+id/checkTue"
android:text="Sat" />
<CheckBox
android:id="#+id/checkSun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkSat"
android:layout_alignBottom="#+id/checkSat"
android:layout_alignLeft="#+id/checkWed"
android:text="Sun" />
<!--
<Button
android:id="#+id/AddTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView1"
android:layout_marginTop="49dp"
android:text="Add Time" />
-->
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Medication Reminder</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="title_activity_med_info">MedInfo</string>
<string name="dose_prompt">Choose a Dose</string>
<string-array name="dose_arrays">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
<string name="check_Monday">Monday</string>
<string name="check_Tuesday">Tuesday</string>
<string name="check_Wednesday">Wednesday</string>
<string name="check_Thursday">Thursday</string>
<string name="check_Friday">Friday</string>
<string name="check_Saturday">Saturday</string>
<string name="check_Sunday">Sunday</string>
<string name="title_activity_daily_med">DailyMed</string>
<string name="title_activity_weekly">Weekly</string>
<string name="title_activity_daily__addtime">Daily_Addtime</string>
<string name="title_activity_interactive_adapter">InteractiveAdapter</string>
<string name="title_activity_interactive_array_adapter">InteractiveArrayAdapter</string>
<string name="title_activity_barcode_scanner">Barcode_scanner</string>
</resources>
try this code.
ActivityMain.class
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener{
LinearLayout list;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ativity_main);
spinner = (Spinner) findViewById(R.id.spinner);
list = (LinearLayout)findViewById(R.id.list);
ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter.createFromResource(this,
R.array.number, android.R.layout.simple_spinner_item);
adapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterSpinner);
spinner.setOnItemSelectedListener(this);
}
public void addButton(int number){
list.removeAllViews();
for(int i = 0; i<number; i++){
Button button = new Button(getApplicationContext());
button.setText("Add Time");
list.addView(button);
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
addButton(1);
break;
case 1:
addButton(2);
break;
case 2:
addButton(3);
break;
case 3:
addButton(4);
break;
case 4:
addButton(5);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_centerHorizontal="true" android:layout_alignParentTop="true"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner" android:id="#+id/list">
</LinearLayout>
strings.xml
<string-array name="number">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
Hope, it will be helpful :)
I created a custom dialog with spinner and OK button. I have populated this spinner with some items and inflated the layout.If I click OK button dialog will dismiss.
I set the spinner
spinner.performCLick();
is there is any way to get spinner selected item and to close the dialog without pressing OK button. I have tried
button.performclick();
but no use.
see my below code it may help you.
package com.Test_dia;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class Test_diaActivity extends Activity {
private Button btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showalert();
}
});
}
protected void showalert() {
// TODO Auto-generated method stub
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.dia);
final String a[] = { "select one", "android", "java", "php" };
Button btnok = (Button) dia.findViewById(R.id.button2);
Spinner spin = (Spinner) dia.findViewById(R.id.spinner1);
btnok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dia.dismiss();
}
});
spin.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, a));
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if (arg2 > 0) {
Toast.makeText(Test_diaActivity.this,
"You Selected :" + a[arg2], Toast.LENGTH_SHORT)
.show();
dia.dismiss();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dia.show();
}
}
main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here" />
</LinearLayout>
dia.xml
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:text="ok" />
This code is work for me perfectly ok.
enjoy....
EDIT (removed previous non-suitable answer)
I'm going to assume that your issue is that using setOnItemSelectedListener is firing 'onItemSelected' on startup (thus selecting the first item in the spinner without any user input) and you don't want that.
If that is the case, try the following.
Set a class variable:
private int newSpinner = 0;
Then in the setOnItemSelectedListener:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
if (newSpinner != 0) {
// Do your code thing here
dismiss();
} else {
newSpinner++
}
}
});
I'm having problems using s.requestFocus() when s is a spinner. Is there a special treatment to get it to work when it's a spinner ?
Thanks
try this code..
spinner.setFocusable(true);
spinner.setFocusableInTouchMode(true);
I'm guessing you aren't literally just looking to "give focus" to the spinner. When you give focus to an EditText, the keyboard pops up, so you may be expecting the spinner selection to "open up" on focus - but it doesn't work that way (don't ask me why). Use s.performClick() to do this - it will act just as if the user clicked on the spinner control.
use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="#+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="#+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="#+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="#+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>
Spinner isn't focusable by default (source). So you have to make it focusable either in xml
<Spinner
android:id="#+id/spinner"
android:focusable="true"
android:layout_width="wrap_conten"
android:layout_height="wrap_content" />
or in code
findViewById(R.id.spinner).setFocusable(true);
I have a simple program where I set a spinner to a position. I then call a second module and when I return, I reset the spinner. The spinner display does not display the spinner value. When you tap the spinner, it IS pointing to the correct value, but it displays an incorrect value. In fact, it actually steps down.
I wrote the following simple program to demonstrate. This only happens when the form has a spinner within either a Linearlayout or TableLayout with at lease 1 other element.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent" android:layout_height="200dp"
android:text="Main Form" />
<LinearLayout android:id="#+id/widget43"
android:layout_width="320dp" android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btn" android:text="Button" android:textSize="16sp"
android:layout_width="160dp" android:layout_height="40dp" />
<Spinner
android:id="#+id/btnFour" android:textSize="16sp"
android:layout_width="160dp" android:layout_height="40dp" />
</LinearLayout>
</LinearLayout>
next.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="#+id/id1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Next"
/>
</LinearLayout>
main.java
package tt.zzz;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class main extends Activity {
#Override
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
fillSpinner();
Button btnGo = (Button) findViewById(R.id.btn);
btnGo.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) { Go(); } });
}
void Go() {
Intent i = new Intent(this, next.class );
startActivityForResult( i, 0 );
}
public void fillSpinner(){
Spinner spin_test = (Spinner) findViewById( R.id.btnFour );
ArrayAdapter<CharSequence> myAdapter =
new ArrayAdapter<CharSequence>(
this,
android.R.layout.simple_spinner_item
);
myAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
myAdapter.add("Option 1" );
myAdapter.add("Option 2" );
myAdapter.add("Option 3" );
spin_test.setAdapter(myAdapter);
spin_test.setSelection(1);
spin_test.setOnItemSelectedListener(
new Spinner.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?>
arg0,View arg1,int arg2,long arg3){
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillSpinner();
}
}
next.java
package tt.zzz;
import android.app.Activity;
import android.os.Bundle;
public class next extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
}
}
After your setSelection, add the following line:
myAdapter.notifyDataSetChanged();
I would do the same as barmaley suggested, except add the following:
#Override
public void onResume()
{
super.onResume();
fillSpinner();
}
The reason why that's needed is because you launch another activity, so this one is paused.
Try to call
#Override
public void onStart()
{
super.onStart();
this.fillSpinner();
}
Since onCreate called only once, so to update Spinner each time you should refresh it somewhere else. onStart() - appropriate place for that