This question already has answers here:
Android - How to create clickable listview?
(5 answers)
Closed 8 years ago.
I currently have a ListView id=listview, which I am populating with an ArrayList id=myarraylist. Here is how I do it:
final ListView listview = (ListView) findViewById(android.R.id.list);
myarraylist = (ArrayList<String>) getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist);
myarraylist.add(...And then some other stuff I add...);
//This is the part I want to focus on
myarraylist.add("Reset High Scores");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
Now, I want the entry Reset High Scores in my ListView to be clickable, and when it is clicked, I want it to do Some Stuff. I know for buttons all you do is set an onClickListener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
..Some Stuff..
}
});
My question is, how can I make Some Stuff happen when the element Reset High Scores is clicked in the ListView
Edit: This is what I have so far
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#Override
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Clear High Scores")) {
//Stuff
}
}
});
ListView, just like Button, has the ability to set a click listener, but for ListView, the name of the method is setOnItemClickListener(). Instead of using OnClickListener, though, it uses a class called OnItemClickListener, which is more advantageous for using with ListView. The method looks as follows:
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
// some stuff
}
}
)
Now the advantage of this is that you can check what's contained at the position you've pressed, so the way you could tackle your problem could look something like this:
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Reset High Scores"))
{
// Do what you want
}
}
});
/**
* Creates a new instance
*/
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
super.onListItemClick(l, v, position, id);
//Do stuff
}
that should get ya started... Andrew is right though.
Related
I have a POJO, which describes some model (Item?) and some custom Adapter.
I am setting my adapter for ListView and then, in onItemClick() I want to get value of one of variables which I had added Into the Item.
How I can reach this?
In my code I am doing something like:
private List<SomeItem> items = new ArrayList();
items.add(new SomeItem(firstValueString, secondValueBitmap, thirdValueString));
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
...
#Override
public void onItemClick(){
//How to reach for example firstValueString value of currently clicked item??
}
)
Use android.widget.AdapterView.OnItemClickListener:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
SomeItem item = items.get(position); // specific item
}
});
Based on Android SDK documentation:
Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item.
If you implement your adapter completely then you can get item like bellow:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item item = (Item)parent.getItemAtPosition(position);
}
});
I have one screen with two spinners. The choices in the second spinner depend on the user choice in the first spinner.
Here is my code:
For the first spinner:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.oman_states));
final MaterialBetterSpinner materialDesignSpinner = (MaterialBetterSpinner)
findViewById(R.id.states_list); // states spinner
materialDesignSpinner.setAdapter(arrayAdapter);
for the second spinner:
final MaterialBetterSpinner materialDesignSpinner2 = (MaterialBetterSpinner)
findViewById(R.id.hospitals_list);
and I implemented the following listener in the second spinner:
materialDesignSpinner2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (materialDesignSpinner.getText().toString() == getString(R.string.muscat)) {
ArrayAdapter<String> muscatHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.muscat_hospitals));
materialDesignSpinner2.setAdapter(muscatHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.albatna)) {
ArrayAdapter<String> albatnaHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.albatan_hospitals));
materialDesignSpinner2.setAdapter(albatnaHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.musandam)) {
ArrayAdapter<String> smaelHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.musandam_hospitals));
materialDesignSpinner2.setAdapter(smaelHospitals);
} else if (gm.spinnerChecking(materialDesignSpinner)) {
Toast.makeText(v.getContext(), getString(R.string.choose_state_first), Toast.LENGTH_LONG).show();
}
System.out.println("Working");
}
});
when I press on the spinner, the application crashes
showing the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Filter.filter(java.lang.CharSequence,
android.widget.Filter$FilterListener)' on a null object reference
at
android.widget.AutoCompleteTextView.performFiltering(AutoCompleteTextView.java:971)
at
com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner.onFocusChanged(MaterialBetterSpinner.java:49)
how can I make the second spinner choices based on the first spinner?
UPDATE:
after applying #dominicoder solution, the onItemSelected is not executed for some reason because System.out.println() doesn't print "work" to the console.
Here is the code for the onItemSelected :
materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
System.out.println("works");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
A couple of things:
Do NOT do string comparisons using == in Java. Use String.equals()
Use the position of the selection of the first spinner to determine what to show, not the text that happens to be showing in that position.
You should update the state of the second spinner in response to the changing of the state of the first spinner, not checking the first spinner state when it's time to show something in the second spinner
You should create just one adapter for your second spinner that you update as needed, instead of creating a new instance each time.
With these suggestions in mind, I would recommend something more like this:
// Second adapter is a class field
private ArrayAdapter<String> secondSpinnerAdapter;
// Initialize it ONCE in onCreate with no items to begin with
secondSpinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line);
materialDesignSpinner2.setAdapter(secondSpinnerAdapter);
// When something is selected in the first adapter,
// update the options in the second adapter
materialDesignSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private String[] getStringsForPosition(int position) {
switch(position) {
case 0: return getResources().getStringArray(R.array.musandam_hospitals);
// Add other cases
}
}
This eliminates string equality checks, removes duplication, and makes the intent "when something in the first spinner is a selected, update the options in the second spinner" much clearer.
Hope that helps!
you shouldn't set an on click listener. instead of that do this
materialDesignSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I have a listview in which previously every item was clickable, and it worked fine. But as soon as I added a feature to have all items long clicked, the onClick feature stopped working. I stripped down all my code for debugging purposes which I will submit here:
listview = (ListView) findViewById(R.id.workout_listview);
listview.setAdapter(new WorkoutListViewAdapter(this, new String[] {...}));
listview.setClickable(true);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.print("CLICK");
}
});
listview.setLongClickable(true);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("LONG CLICK");
return true;
}
});
This code causes nothing to happen when a list item is clicked and displays "LONG CLICK" when one is long clicked.
I found this question, which seems to have the same problem but the code is structured very differently, and my code is already following the answer's guidelines of implementing the listener on the ListView rather than the row.
I would like to call an action every time my spinner selects a new item. The current setup is that an action is called when a button is pressed.
My approach:
Create a new function: public void onSpinnerItemSelection(View V){...}
Then in content_home.xml I would add onSpinnerItemSelection to onClick for Spinner.
This isn't working. I'm not familiar with Android errors and I'm struggling to interpret these errors.
Unfortunately, myApp has stopped
Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
Step by step:
1ªDeclare variables from the layoutSpinner sp; the arraylist in this case ArrayList listTeams; and the adapter Adapter adapter;
2ªinstances
private void instances() {
sp = (Spinner) findViewById(R.id.spinner);
listaTeam = new ArrayList();
3º add items for the adapter
private void listAdapter() {
listaTeam.add(new Equipo(R.string.Atleti));
adaptador = new Adaptador(MainActivity.this, listaEquipo);
sp.setAdapter(adapter);
now we make actions, use onItemSelected.
public void onItemSelected(AdapterView parent, View view, int position, long id) {
Toast.makeText("this is my team", Toast.LENGTH_LONG).show();
}
https://www.youtube.com/watch?v=H3W0-Nv664I
Here is an example:
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText("log", "position = " position, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText("log", "onNothingSelected", Toast.LENGTH_LONG).show();
}
});
Hi i have the following ListView code:
{
// Populate the wordsList with the String values
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,matches));
}
I would like a listener which when it finds the string "start" from wordsList it does a if statement, I have tried for the past many hours but cannot get anywhere.
Do you mean something like that?
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (myList.getAdapter().getItem(position).equals("Start")) {
//Do your stuff here
}
}
});
In that case, the listener will be called when the user clicks on the item which text is "Start". Is that what you want?