I have been trying to solve this simple problem for two days now without success. I know a similar question have been asked before (like here:
How do you get the selected value of a Spinner? ), but I haven't been able to solve this yet.
So, I have created a simple app which contains a spinner and a custom ListView. The spinner (containing values 1,2,3,4,5..) creates more spinners (which contain Player names) to the ListView (eg. choosing 4 creates four spinners). Currently, the program works fine except that I don't know how to get the selected values of the spinners in ListView when clicking a button in Action Bar? I tried to use getItemAtPosition and getSelectedXXX() methods but I always tend to the get values from a single spinner I recently selected.
I am not sure do I have to invoke the methods in the Spinner's setOnItemSelectedListener(), or can I call the values from outside the SpinnerAdapter class.
Here is the custom Spinner class
public class PlayerAdapter extends ArrayAdapter<String> {
public PlayerAdapter(ArrayList<String> mPlayers) {
super(getActivity(), 0, mPlayers);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_players, null);
}
Spinner mSpinnerPlayer = (Spinner) convertView
.findViewById(R.id.spinner_player);
ArrayAdapter<Player> spinnerAdapterPlayer = new ArrayAdapter<Player>(getActivity(), android.R.layout.simple_spinner_item, mPlayers);
spinnerAdapterPlayer.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPlayer.setAdapter(spinnerAdapterPlayer);
mSpinnerPlayer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
//Should I use getItemAtPosition or getSelectedXXX methods here?
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
return convertView;
}
}
}
Here is the Fragment which inflates the layout creates the first spinner (sorry about the formatting and code style)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
//gets player names from a database, such as "Player 1", "Player 2" etc..
//this is container of the spinners displayed in the listview
mPlayers = PlayerDB
.get(getActivity())
.getPlayers();
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_menu, parent, false);
listView = (ListView) view.findViewById(R.id.listView1);
mSpinnerNumOfPlayers = (Spinner) view.findViewById(R.id.spinner_numOfPlayers);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter
.createFromResource(this.getActivity(),
R.array.numberOfPlayers_array,
android.R.layout.simple_spinner_item);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerNumOfPlayers.setAdapter(spinnerAdapter);
mSpinnerNumOfPlayers.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String position = parent.getItemAtPosition(pos).toString();
mArray = new ArrayList<String>();
posInt = Integer.parseInt(position);
for (int i = 0; i < posInt; i++) {
mArray.add("" + i);
}
PlayerAdapter adapter = new PlayerAdapter(mArray);
listView.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
}
);
return view;
}
// ActionBar
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_start:
//when "start" button is clicked the spinner values are saved into an ArrayList
This method will retuns you the selected ite from the spinner..
spinner.getSelectedItem().toString()
Related
I wanted to display selected item in the textView when selected from dropdown list of spinner I implemented AdapterView.OnItemSelectedListener but when I'm selecting item its always null/empty here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new CustomAdapter(MainActivity.this, Languages));
btn.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
item = (String)parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
SO answer source: https://stackoverflow.com/a/49301966/5461982
I know this is an older question now but if anyone else comes across it be sure to check that your custom implementation of the Adapter you're setting for your Spinner overrides the getItem method:
#Override
public Object getItem(int position) {
return spinnerItems.get(position);
}
By default, you're required to override this method when implementing a custom BaseAdapter but the default return type is null. Be sure to modify the return type to return spinnerItems.get(position).
Hope this helps, I spent around 30 mins trying to work this out originally!
Try this,
String selected_item = spinner.getSelectedItem().toString();
Just retrieve value from String Array:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String item = Languages[position];
Toast.makeText(MainActivity.this, item, Toast.LENGTH_SHORT).show();
}
try this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
sSelectedItem = arr_spiner.get(spinner.getSelectedItemPosition())
.getName();
txtSpinnerValue.setText(sSelectedItem);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
https://stackoverflow.com/questions/45159011/spinner-item-is-not-visible-data-is-coming-from-server-android/45161202#45161202
Try This
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new CustomAdapter(MainActivity.this, Languages));
btn.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
//item = (String)parent.getItemAtPosition(position);
item = (String) spinner.getSelectedItem().toString(); //Here is the Change
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
The change here is
From
item = (String)parent.getItemAtPosition(position);
TO
item = (String) spinner.getSelectedItem().toString();
I have multiple spinners with a string array that has 3 items called "70","80" and "90". After the user selects these different spinner items I want to be able to sum up all of the items which the user has selected and display the total in a textview.For example a user selects "70" from one spinner and "70" from another, a textview will show the total 140. How can I do this?
public class FragmentCalc3 extends Fragment{
Context context;
TextView Results;
public static FragmentCalc3 newInstance()
{
FragmentCalc3 fragment = new FragmentCalc3();
return fragment;
}
public FragmentCalc3() {}
// Required empty public constructor
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_calculator3, container, false);
Results = (TextView) rootView.findViewById(R.id.Results);
context = container.getContext();
final Spinner spinner1 = (Spinner) rootView.findViewById(R.id.TestSpinner2);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(context, R.array.GradeTest, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner1.setAdapter(adapter1); // Apply the adapter to the spinner
final Spinner spinner2 = (Spinner) rootView.findViewById(R.id.TestSpinner1);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(context, R.array.GradeTest, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner2.setAdapter(adapter2); // Apply the adapter to the spinner
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int spinner2Value = Integer.parseInt(spinner2.getSelectedItem().toString());
int spinner1Value = Integer.parseInt(spinner1.getSelectedItem().toString());
int Results = spinner2Value + spinner1Value;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
}
If you have two spinners spinner2 and spinner1, And you want to get result when item of spinner2 is selected then simply do like this,
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int spinner2Value = Integer.parseInt(spinner2.getSelectedItem().toString()); //Add try catch block if necessary
int spinner1Value = Integer.parseInt(spinner1.getSelectedItem().toString());
int yourResult = spinner2Value + spinner1Value; //Result
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
//Do nothing
}
});
I'm creating spinner programmatically spinner show perfectly dropdown but when I click ant item is not show Toast message when I debug is not go inside spinner click method what is wrong in my code? spinner item will show but click event not work what is wrong?
public class MainActivity extends Activity {
Spinner spinner;
String[] strings = { "Power Options", "Power off", "Restart" };
String[] subs = { "", "Shut phone down", "Close all apps and restart phone" };
int arr_images[] = { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinner = new Spinner(this);
spinner.setAdapter(new MyAdapter(this, R.layout.row, strings));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {
// TODO Auto-generated method stub
if (i == 1) {
Toast.makeText(MainActivity.this, "PowerOff Perform",
Toast.LENGTH_SHORT).show();
}
if (i == 2) {
Toast.makeText(MainActivity.this, "Reboot Perform",
Toast.LENGTH_SHORT).show();
}
}
// If no option selected
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
TextView label = (TextView) row.findViewById(R.id.company);
label.setText(strings[position]);
TextView sub = (TextView) row.findViewById(R.id.sub);
sub.setText(subs[position]);
ImageView icon = (ImageView) row.findViewById(R.id.image);
icon.setImageResource(arr_images[position]);
return row;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
spinner.performClick();
return true;
}
return super.onKeyDown(keyCode, event);
}
maybe use setOnItemClickListener instead of setOnItemSelectedListener ?
Try to use
spinner.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
}
});
instead of
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {...
I am struggling with trying to implement an OnLongClick feature - I can't understand where to add a listener and to define the resulting method.
The implementation i have used uses an adapter - and does not have an onClickListener, but works jsut fine. can anyone suggest where/how to implement OnLongClick listener
I don't need every item in the list to perform different actions - just for anywere on the screen to pick up the long press
public class CombChange extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ListEdit(this, symbols));
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
}
public class ListEdit extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListEdit(Context context, String[] values) {
super(context, R.layout.activity_comb_change, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_comb_change, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
if (s.equals("a")) {
imageView.setImageResource(R.drawable.a);
return rowView;
}
}
Try this:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
v.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
return false;
}
});
}
It is unfortunate that a ListActivity does not have a protected onListItemLongClick() method similar to the onListItemClick() function.
Instead, you can add setOnLongClickListener() to the top-level layout item (or any View) in your adapter's getView() function.
Example:
myView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something here.
return true;
}
});
Warning, the OnLongClickListener you put onto your list item may hide exposure to the onListItemClick() function you already have working for the list. If this is the case, you will also have to add setOnClickListener() to getView() and use it instead.
in your getView you can say
rowview.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
//Do your stuff here
return false;
}
});
i m developing an application in which gridview contain list of button...
when i place images instead of button in gridview then onItemClickEvent get fired..but if i place button in gridView then click event not getting callled...i dont know what is the problem...even i m not getting exception..
here is my code...
public class MainMenu extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.mainMenu);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(MainMenu.this, "hello" + position, Toast.LENGTH_SHORT).show();
}
});
}
//inner class for adapter
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
//ImageView imageView;
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn=new Button(mContext);
// imageView = new ImageView(mContext);
btn.setLayoutParams(new GridView.LayoutParams(120,120));
// imageView.setLayoutParams(new GridView.LayoutParams(140,140));
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
btn.setPadding(10,15, 10,15);
btn.setImeActionLabel("hello",0);// actionId)
// imageView.setPadding(8,8, 8, 8);
} else
{
btn=(Button)convertView;
//imageView=(ImageView)convertView;
}
btn.setBackgroundResource(mThumbIds[position]);
//imageView.setImageResource(mThumbIds[position]);
//return imageView;
return btn;
}
// references to our images
private Integer[] mThumbIds =
{
R.drawable.pantrylocator_icon,
R.drawable.volunteeropportunity_icon,
R.drawable.volunteerlocator_icon,
R.drawable.volunteermanagement_icon,
R.drawable.donationform_icon,
R.drawable.donationviamsg_icon,
R.drawable.donationvideo_icon,
R.drawable.virtualfooddrive_icon,
R.drawable.newevent_icon,
R.drawable.pressrelease_icon,
R.drawable.volunteerphotos_icon,
R.drawable.aboutus_icon,
};
}
}
The button has its own OnClickListener:
public View getView(int position, View convertView, ViewGroup parent) {
//ImageView imageView;
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn=new Button(mContext);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
// imageView = new ImageView(mContext);
btn.setLayoutParams(new GridView.LayoutParams(120,120));
// imageView.setLayoutParams(new GridView.LayoutParams(140,140));
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
btn.setPadding(10,15, 10,15);
btn.setImeActionLabel("hello",0);// actionId)
// imageView.setPadding(8,8, 8, 8);
} else
{
btn=(Button)convertView;
//imageView=(ImageView)convertView;
}
btn.setBackgroundResource(mThumbIds[position]);
//imageView.setImageResource(mThumbIds[position]);
//return imageView;
return btn;
}
In your ImageAdapter-> getView method add the following line before returning newly created "convertView"
convertView.setClickable(false);
convertView.setFocusable(false);
If any of the views in gridview are clickable then they will block the grid's ItemClick listener from responding.
There is no onclick event written for the Buttons you are adding. Write code for the buttons to handle the click event! let us know then.
i have fece this problem also but finally got the solution i have follow the above suggession
and define button click event in base adapter class like as
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = LayoutInflater.from(mContext);
v = li.inflate(R.layout.icon, null);
tv = (Button)v.findViewById(R.id.icon_text);
iv = (ImageView)v.findViewById(R.id.icon_image);
iv.setImageResource(mThumbIds[position]);
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(mContext, "vim", Toast.LENGTH_LONG).show();
}
});
}
else
{
v = (View)convertView;
}
return v;
}
gridview = (GridView) findViewById(R.id.gameGrid);
gridview.setAdapter(ia);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Ur Code here
}
Add click events for the button added in gridView
Here's the cleanest way to do it: call performItemClick() on the GridView from within each button's click listener. That way you can still use the GridView's onItemClickListener like normal.
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((GridView) parent).performItemClick(v, position, 0);
}
});
}
http://www.migapro.com/click-events-listview-gridview/
I have solved my problem as i define button click event in base adpter class and my problem is solved......