Using Spinner to change layouts - android

Using the below code I want to simply change layouts upon spinner value selection. However, when my activity loads, the spinner never loads the values to be selected.
Oddly enough when I remove the code for (and everything below it)
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
the spinner values show up again.
public class ListCarsActivity extends Activity implements OnItemClickListener, OnClickListener, OnItemSelectedListener {
public static final String TAG = "ListCarsActivity";
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_cars);
spinner = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter adapter= ArrayAdapter.createFromResource(this,R.array.domain,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
// initialize views
initViews();
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long row_id) {
switch(position){
case 1:
setContentView(R.layout.list_cars);
break;
case 2:
setContentView(R.layout.list_owners);
break;
}
setContentView(R.layout.list_cars);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

The spinner you are referring to is in your first activity. After you have replaced the content, the spinner isn't there anymore. If you have another spinner in the second layout, you have to reconnect it and set the listener again. Basically you have to run your onCreate stuff after every setContentView...
As a side note, whatever you are trying to do, this is probably not the way to go. To show another full layout, better use another activity.

Related

"If Spinner = Value Then" in Android Studio

It's Will Be Good For Your Help,,
i have 2 Spinner + Mediam Text + Button
First Spinner "hint" [where i'm Now]
(Los angeles, California, London)
Second Spinner "hint" [i Want To Go]
(Florida, Origin, London)
When i Click On Button, Will Show Result in Text Box ..
Example:
When I choose I'm in "Los angeles" And Want To Go "London" Then Result Will Show in Text Box, that Says "If you Want Go To London You Have To Travel with Airplane".
Please explain because I'm Lv1 in Android Studio.
Try this code..!
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
Spinner temp1,temp2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
t1=(TextView)findViewById(R.id.t1);
temp1=(Spinner)findViewById(R.id.temp);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this,R.array.temperature,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
temp1.setAdapter(adapter);
temp2=(Spinner)findViewById(R.id.temp2);
ArrayAdapter<CharSequence> adapter2=ArrayAdapter.createFromResource(this,R.array.temperature,android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
temp2.setAdapter(adapter2);
temp1.setOnItemSelectedListener(this);
temp2.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner temp1=(Spinner)parent;
Spinner temp2=(Spinner)parent;
if (temp1.getId()==R.id.temp) {
String item = parent.getItemAtPosition(position).toString();
t1.setText(item);
}
if (temp2.getId()==R.id.temp2) {
String item = parent.getItemAtPosition(position).toString();
t1.setText(item);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Android dependent spinners - onItemSelected does not fire

I tryed to create two dependent spinners. I know there is more than enough of this type of question, but nothing fixed my problem. It seems onItemSelected does not fire at all. I want the second (townships_spinner) change when first spinner (divisions_spinner) is selected or changed. Let's say I have states and cities, when I select the state a want to display only cities from given state. Spinners are created dynamicaly.
That's my code:
public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
createLayout();
}
public void createLayout(){
division_spinner = new Spinner(this);
ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList());
divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
division_spinner.setAdapter(division_adapter);
division_spinner.setSelection(divisions.getIndex(divisions_id));
division_spinner.setOnItemSelectedListener(this);
township_spinner = new Spinner(this);
ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id));
if (divisions_id == null) {
township_spinner.setEnabled(false);
}
String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
township_spinner.setSelection(townships.getIndex(value, divisions_id));
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG);
if(arg0.equals(division_spinner)) {
Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG);
township_spinner.setEnabled(true);
ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString()));
township_spinner.setAdapter(township_adapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But "Yes" even "Yes - you got it!" toast does not appear.
I guess I miss something stupid, but I cant find it.
you're implementing AdapterView.onItemSelected.
...Just try this instead
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show();
//Call other spinner here to update.
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show();
}
});
Edit: as Prasad says. If you don't have setContentView(View); your activity won't have an xml to inflate, so your views will never get created into anything.
I made a series of mistakes that led to the fact that it did not work as I expected.
First: I forgot to call **show()** on Toast.makeText()
Second: I make a huge mistake when creating ArrayList. I filled ArrayList with data, then I put the list to HashMap and after that I called ArrayList.**clear()**. Which led to override the HashMap values, and that was why it seemed, the spinner was not changing at all...
Well... I feel quite silly ...

Android Spinner: Cannot selected

I have the code, which unfortunately does not work as it should. More specifically, we can not choose from the second spinner. Here is the code. Thank you in advance for your help.
public class Zamiana extends Activity {
public Spinner spinner1;
public Spinner spinner2;
final ArrayList<Spanned> kon = new ArrayList<Spanned>();
[...]
spinner1 = (Spinner) findViewById(R.id.test);
spinner2 = (Spinner) findViewById(R.id.test2);
ArrayList<Spanned> adapter = new ArrayList<Spanned>();
adapter.add(Html.fromHtml("t0"));
adapter.add(Html.fromHtml("t1"));
adapter.add(Html.fromHtml("t2"));
[...]
ArrayAdapter<Spanned> kontrol = new ArrayAdapter<Spanned>(this,
android.R.layout.simple_spinner_item, adapter);
kontrol.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(kontrol);
spinner1.setOnItemSelectedListener(wyznacz);
spinner1.setOnItemSelectedListener(wyznacz);
ArrayAdapter<Spanned> kontrola = new ArrayAdapter<Spanned>(this,
android.R.layout.simple_spinner_item, kon);
kontrola.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(kontrola);
}
public OnItemSelectedListener wyznacz=new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
switch(arg2){
case 0:
kon.clear();
kon.add(Html.fromHtml("t0"));
break;
case 1:
kon.clear();
kon.add(Html.fromHtml("t1"));
break;
case 2:
kon.clear();
kon.add(Html.fromHtml("t2"));
break;
[...]
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
Thanks you very much for all help :)
For the spinners I have created I have only used three methods that I would override (onCreate, onItemSelected, onNothingSelected). I am confused why you have an OnItemSelected Listener above your onItemSelected Method since the onItemSelected Method is called when an item is selected.
It's not the best answer and more detail of what your spinner is suppose to achieve would be great but having the onItemSelected Method within an OnItemSelected Event Listener just seems to kind of stand out above everything else.
Hope this helps or points you in the right direction. Good Luck! plus post more code and details about your spinner.

Android Spinner - onItemSelected / setOnItemSelectedListener not triggering

This is driving me nuts since it's something I've done before but can't figure out why it isn't working now...
I've got a menu button, implemented in the usual way via a menu.xml file and the onOptionsItemSelected method with a switch in it, that creates and displays a spinner.
I've added the setOnItemSelectedListener, but it never seems to trigger. The spinner appears, I pick an option or back out, neither onItemSelected or onNothingSelected are called.
Here is all the code between the "case" and "return true" of the menu-button-handling switch statement. (topThis is a variable referring to the context of the activity - works fine for all other toasts in the app)
String[] widgetModes = {"Mode 1", "Mode2"};
ArrayAdapter<String> widgetModeAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, widgetModes);
widgetModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner widgetModeSpinner = new Spinner(this);
widgetModeSpinner.setAdapter(widgetModeAdapter);
widgetModeSpinner.setPrompt("Choose Widget Mode");
widgetModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "derp", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
widgetModeSpinner.performClick();
Any ideas? I vaguely suspect that the fact I'm creating the Spinner programmatically is the problem...
I had the similar problem when I was implementing a spinner, I resolved it by getting the parent View and set Adapter-
spinner1 =(Spinner)findViewById(R.id.spinner1);
spinner1.setAdapter(BindSpinner("ProgramMaster",cols,null,true,""));
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
protected Adapter initializedAdapter=null;
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
if(initializedAdapter !=parentView.getAdapter() ) {
initializedAdapter = parentView.getAdapter();
return;
}
String selected = parentView.getItemAtPosition(position).toString();
if(abc.equals("Select") && !selected.equals("Select"))
{
do something
}
else
{
Do something
}
textQualification=selected;
SearchUpdated("Qualification");
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Remember that you can't re-select the same spinner item, it always sets the first item as selected if you are not adding some custom code to handle the spinner selection.
For the Toast not showing, I would suggest to always use the "MyActivity.this" as your context when creating a Toast inside a listener interface like this:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item is selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An spinnerItem was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast.makeText(MyActivity.this, "Hello Toast",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing, just another required interface callback
}
}); // (optional)
And the .show() at the end is easy to forget sometimes;)
Actually, if your spinner visibility is set to gone then it will trigger the click of it when you call performclick() method but it will not trigger its setOnItemSelectedListener
so you need to change the visibility then it will work
I know the question is a bit old, but in case you are waiting for a AsyncTask callback, make sure that you let your adapter know of the data changes by calling notifyDataSetChanged() on the callback thread!
#Override
public void onPostExecute(String result) {
///do something with your data
spinnerArrayAdapter.notifyDataSetChanged();
}

Android custom listview, setOnItemSelectedListener not working

I'm just beginning Android development, and I'm working to get a Custom listview with a checkbox working. I've created a base class that extends Activity, Created an Adapter and overrode the getView() method to add the checkbox to the listview. I'm assuming I need to do this because I need something equivalent to didSelectRowIndexAtPath from Obj C to update my model. Please let me know if there's an alternate way of doing this too!
Now in my base class, I have the following code -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout);
setContentView(R.layout.facilityscreen);
/* Static Data source */
facilityModel = new FacilityDataModel[2];
facilityModel[0] = new FacilityDataModel();
facilityModel[1] = new FacilityDataModel();
facilityModel[0].setFacilityName("Test 1");
facilityModel[0].setFacilityID("Facid0001");
facilityModel[0].setChecked(false);
facilityModel[1].setFacilityName("Test 2");
facilityModel[1].setFacilityID("Facid0002");
facilityModel[1].setChecked(true);
facilityListView = (ListView) findViewById(R.id.facilityListView);
FacilityScreenAdapter adapter = new FacilityScreenAdapter(this, facilityModel);
facilityListView.setAdapter(adapter);
myPatBtn = (Button) findViewById(R.id.myPatBtn);
myPatBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int i=0;
i++;
}});
facilityListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int i=0;
i++;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My problem now is the setOnItemSelectedListener isn't getting called at all. Been struggling with this for a couple of hours now, and I can't figure out why it wouldn't get called at all.
Any help is much appreciated!
Thanks,
Teja.
I know this is an outdated answer but I'm going to write it just in case some other fellow who has the same "problem" bumps onto this page :
The solution to the above problem which is not a problem but just a misunderstanding is that the ListView.onItemSelected() event is fired up, upon :
1) Navigating through the emulators-cross handles or
2) as far-as my HTC-Hero is concerned, the rolling-action on the white little roller-ball.
You don't have to extend your activity explicitly to a ListActivity.
Here's my tiny little code which retrieves a phone number from
a TextView control, inside a listview item.
When the user either touches the list item or scrolls through the list with
the little roller-ball the below Events, fire up and MakeACall() method is called :
myList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
});
myList.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I hope that was helpful... :)
There exists already the possibility to have a ListView with checkboxes.
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
I've taken this from the APIDemos 'cause it was the simplest. You can then get the selected items by using:
long[] selectedIds = getListView().getCheckItemIds();
What you may also be interested in is the CheckedTextView which is used internally in the list.
To the part of the onListItemClick problem
Try to extend from ListActivity rather than Activity. Then override the onListItemClick. That should work.
use
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// here you code
}
})
instead of setOnItemSelectedListener
As setOnItemSelectedListener is called when item is being selected not clicked so to get clicked item you must use setOnItemClickListener this will work
You should set all focusable items in custom list layout to false:
android:focusable="false"
also I think you should not use attributes like android:clickable="true" for them.
The lack of the item selected listener getting called is by design and is based on which mode the device is in. In touch mode, there is no focus and no selection. Your UI should use widgets that differentiate between touch for selection versus touch for scrolling. Radio buttons, for example, are good when there is a single selection choice.

Categories

Resources