How to Open a Custom Spinner Item from MainActivity? - android

I have two activities viz., Activity A and B and I have a spinner in Activity B with 5 options(like country names). On clicking an item, a toast is shown to the user.
//Performing action onItemSelected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
}
In my Activity A, I use a button to open Activity B using Intent. The activity B is opened with the first item of the spinner.
Question
Is there a way so that on clicking the button in Activity A, second spinner item is opened and the respective toast is shown?

you can use the setSelection(int item) method of your spinner (see: https://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)).
For example:
//Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
//find spinner
spinner.setSelection(1)
}

This answer is based on the assumption that you want to set 2nd item of the array as the default selection.
Use the following code:
final Spinner spinner = (Spinner) view.findViewById(R.id.spinner1);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.names));
spinner.setAdapter(arrayAdapter);
spinner.post(new Runnable() {
#Override
public void run() {
spinner.setSelection(1);
}
});
I am late now I think...

Related

Using Spinner to change layouts

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.

Android onItemLongClick adds position to the arrayList in different activity

I have got two activities.
My goal is: After longClick on any ListView position in activity 2, I want some String to be added to ListView in activity 1. From activity 2 I'm going back to activity 1 by pressing back button. Each ListView has got different adapter.
I tried with Bundle (put extra), but it makes app crash.
Fragment of code from activity 1:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() { //It adds text ect. to listView - It works so I cut out the rest of code
ar.add("anything");
ar.add(lv.try);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
});
}
Simply adding like ar.add("anything"); works. The lv.try contains by default text "First text". I tried to update this variable in activity 2 onItemLongClick fragment of code:
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//What to type here?
return false;
}
});
Putting simply try = "Second text"; will not update my try variable. I tried also with Bundle (extras) but without success. Any ideas?
I don't know if I understood the question. Anyway, have you tried to override onBackPressed?
In the second activity you create a boolean variabile and inizialize it as false, then change its value when you perform a long click:
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClick = true;
return false;
}
});
Remember, longClick has to be a class variable!
Outside onCreate:
#Override
public void onBackPressed() {
Intent intent = new Intent(SecondActivityName.this, FirstActivity.class);
intent.putExtra("longClick", longClick);
finish();
startActivity(setIntent);
}
And in the first Activity:
Intent intent = getIntent();
if (intent.getBooleanExtra("longClick", false)) {
addDrawerItems();
}
What does add position mean ?
In my opinion add position means add one element to a structure (array, list, etc).
So basically what I mean is that you can have an array in your CustomApplicatioClass or even a Static array(someone probably would not agree with me) and onItemLongClick() add the element you want in the structure.
Then when you load the Activity with the ListView you can do your ListView stuff using the updated structure
hope it helps

Spinner OnItemSelectedListener Issue

I have problem with spinner control. I am trying to set spinner items dynamically. Initially I have one item in spinner.
When I try to register the spinner.setOnItemSelect Listener, it immediately call onItemSelected method of it. However I don't want to call this method as soon as my activity get started.
So for this I put a following condition.
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
Spinner spinner;
String[] str_arr = {"aaaaaaaa"};
private int mSpinnerCount=0;
private int mSpinnerInitializedCount=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str_arr));
spinner.setOnItemSelectedListener(this);
mSpinnerCount=1;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (mSpinnerInitializedCount < mSpinnerCount) {
mSpinnerInitializedCount++;
}
else {
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But when I try to select an item on spinner it gives following warning in logcat,
09-03 13:02:02.528: W/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#450fafb8
I get the idea that until and unless Item of spinner won't change this method won't be called.
But I have one value in spinner, so how to get the focus, any idea?
Try this to what i said in comment...
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (position > 0) {
//Your actions
}
else {
// Nothing or can show a toast to say user to select a value...
}
}
Try like this
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if (position != 0) {
//put your actions here
}
else {
// nothing here or toast
}
}
I think the below code are not right because you implements OnItemSelectedListener
spinner.setOnItemSelectedListener(this);
You get this warning when you try to open already opened window, or try to do something like onFocus on already focused view.
Here you already have the item selected in the Spinner

Dynamically adding items to listview

I am making an android application that needs to use a ListView. Once a user presses a menubutton, it pops up a popupwindow containing a TextView, EditText and two Buttons, "Ok" and "Cancel". Once the user presses "Ok", the text inside the EditText should be added to the ListView. And the cancel Button is obvious. I also want to be able to long press on a ListView item to open a popupwindow containing a delete Button. How can I make this possible? I am using this code so far:
public class NotesActivity extends ListActivity {
/** Called when the activity is first created. */
Button AddItemToListView;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
Toast.makeText(NotesActivity.this,
"Add note button pressed", Toast.LENGTH_SHORT)
.show();
break;
}
return true;
}
}
Try doing some research on dialogs if you want to add feature after accessing listview.setonlongclick(). Here is a link on android dialog developers.
Since you are using an ArrayAdapter, when the user taps on add, you must add the new item to your array (change from an array to an List to make it easier). Then you should call notifyDataSetChanged() from the ArrayAdapter.
For deleting is the same, but you remove the item from the List. The call to notifyDataSetChanged() is to tell the ListView that it needs to redraw itself.

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();
}

Categories

Resources