I know there is a lot of information out there about using the onItemClickListener and list view but I am new to android development and cannot seem to get it working.
I am not quite sure where I should add the listener so I would really appreciate some help and guidance.
I have two files, the main activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ArrayList<GroceryList> menuitems = getItems();
ListView listView = (ListView) findViewById(R.id.Menu);
listView.setAdapter(new GroceryListAdapter(this, R.layout.categorymenu, menuitems));
}
and the ListAdapter File:
public class GroceryListAdapter extends ArrayAdapter<GroceryList> {
private ArrayList<GroceryList> grocerylists;
private Activity activity;
public ImageManager imageManager;
public GroceryListAdapter(Activity a, int textViewResourceId, ArrayList<GroceryList> grocerylists) {
super(a, textViewResourceId, grocerylists);
this.grocerylists = grocerylists;
activity = a;
}
public static class ViewHolder{
public TextView name;
public TextView message;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.categorymenu, null);
holder = new ViewHolder();
holder.name = (TextView) v.findViewById(R.id.categoryname);
holder.message = (TextView) v.findViewById(R.id.message);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final GroceryList grocerylist = grocerylists.get(position);
if (alcohollist != null) {
holder.name.setText(grocerylist.name);
holder.message.setText(grocerylist.message);
}
return v;
}
I am sorry if I am asking a question that has already been answered but I spent a lot of time trying to figure it out for myself but with no success.
I hope some one with more experience than myself will be able to tell me where and how I should add the onItemClickListen method.
Thanks!
By the looks of it you are using a regular Activity, so you should add this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "You clicked item at position"+position,
Toast.LENGTH_SHORT).show();
}
});
BEFORE the .setAdapter in your main activity. That should work.
In your Main activity:
listView.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(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
// startActivity( new Intent());
Intent i = new Intent(this,"Next_Activity_Name".class);
i.putExtra("selected",(int)selected_position);
final int resultCode = 2;
startActivityForResult(i,resultCode);
}
You have to add this piece of code into ur main activity after the onCreate() method..
Write down the following code after setting the adapter.
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}});
Handle the functionality that you want to do on click, under the onItemClick method.
you have use custom adapter so you can set touchListner at perticular widget which you define in categorymenu layout. it is quit easy to do this but
if you use simple listview then
Add parameter in listview :
lview.setOnItemClickListener(this);
public void onListItemClick(ListView parent, View v, int position, long id) {
// do with list-view item Position
}
For more ....
Simple Listview
http://www.androidpeople.com/android-listview-onclick
http://developer.android.com/resources/tutorials/views/hello-listview.html
http://mobile.tutsplus.com/tutorials/android/android-listview/
Paresh Mayani
Custome Listview
http://saigeethamn.blogspot.com/2010/04/custom-listview-android-developer.html
how to customize listview row android
http://www.josecgomez.com/2010/05/03/android-putting-custom-objects-in-listview/
Here so many answers, But it seem to be you didn't understood what they are telling. I will also try to give answer.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ArrayList<GroceryList> menuitems = getItems();
ListView listView = (ListView) findViewById(R.id.Menu);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// do whatever you want on clicking any list itm
}
});
listView.setAdapter(new GroceryListAdapter(this, R.layout.categorymenu, menuitems));
}
I hope you will understand it.
Related
I have a fragment which extends ListFragment.
In it I use an ArrayAdapter
public class MyFragment extends ListFragment {
public void onStart() {
super.onStart();
List<String> list = new ArrayList<String>();
list.add("Superman");
list.add("Batman");
arrayAdapter = new ArrayAdapter<OptionToStringAdapter>(
getActivity(),
android.R.layout.simple_list_item_1,
list);
getListView().setAdapter(arrayAdapter);
getListView().setOnItemClickListener(new ModifyOption(this));
setListShown(true);
}
When the user taps an item I want to modify the text.
How do I modify the text?
public class ModifyOption implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
???What goes here????
}
}
Assuming you want to change the content of the list item you clicked.
First, change the value using a dialog or widget of your choice.
Second, change the value of the item at the position in the list by using 'position' argument.
Third, call notifyDataSetChanged() method of the adapter object.
public class ModifyOption implements OnItemClickListener {
public void onItemClick(AdapterView parent, View view, int position, long id) {
// create a dialog or other widget
String newValue = "your_new_value";
list.set(position,newValue);
arrayAdapter.notifyDataSetChanged(); //informs views that data has been changed
}
}
try with below code:
public class ModifyOption implements OnItemClickListener { public void onItemClick(AdapterView parent, View view, int position, long id) {
arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.insert("new text",position);
} }
This seems to do the trick. I don't know if this is an appropriate way though.
public void onItemClick(AdapterView parent, View view, int position, long id) {
TextView textview = (TextView) view.findViewById(android.R.id.text1);
textview.setText("Spiderman");
}
What I have tried:
public class EntryAdapter extends ArrayAdapter<Item> {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
// // // // NON-FUNCTIONING CODE BELOW
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), NewsItemActivity.class);
convertView.getContext().startActivity(intent);
}
};
}
The AdapterView.onItemClickListener doesnt yield any errors but doesnt seem to function whatsoever.
What is the proper way of setting this onClick Listener?
Note: I have to set it in this adapter class, not the main class for my own reasons.
You shuldn't implement a listener inside the getView() unless you what set a listener on a particular view inside your row layout.
You should instead use setOnItemClickListener() method on your ListView:
ListView lv = (ListView) findViewById(R.id.your_listview);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(context, NewsItemActivity.class);
context.startActivity(intent);
}
});
EDIT:
If, for each action inside the onclick, you need information that resides in your Objects (Item) then you can get it in this way:
Item item = (Item)listview.getAdapter().getItem(position);
from inside of onItemClick() method
You can use:
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make what you want
}
});
Or depending on your item view, you can make the OnCLickListener on your global layout of the item or a specific item's layout
Try by this code :-
Spinner cb_tv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
list.add(phone1);
list.add(name1);
dataAdapter = new ArrayAdapter<String>(Display_Tank.this,android.R.layout.simple_spinner_item, list);
cb_tv.setAdapter(dataAdapter);
cb_tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
}
});
at the place of cb_tv Spinner You can use ListView
First of all, the best way to achieve this is to use your own ViewHolders in ListView.
This is an example of a custom ViewHolder
class MyViewHolder extends ViewHolder implements View.OnItemClickListener {
public MyViewHolder(View view) {
/* Implement your views here
* like this: mTextView = (TextView) view.findViewById(R.id.myId);
*/
view.setOnItemClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), NewsItemActivity.class);
convertView.getContext().startActivity(intent);
}
}
And on your getView method you create this ViewHolder and populate your Views with your data.
You can try this way... it is working in my case Change your context to
Activity activity = (Activity) context;
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, NewsItemActivity.class);
activity.startActivity(intent);
}
});
I am having a layout consisting of ListView and a label. Look at the image below.
I implemented listview using base adapter in a seperate .java file.
Could anyone suggest me how can i set text to the label on click of list item?
EDITED :
The text of the label should be number of list items clicked.
Suppose i clicked a button in a list item, the label should be set to 1.
Similarly in the next attempt if i clicked another list item's button it should be set to 2 and so.. on..
Sir,
What you are saying is this, you have your adapter in one class and the activity in another file. Well you could do this, to update the textview.
pass the context to the activity, and if its in the adapter you are maintaining the count then once the count has been updated,
then, assume you have this method in the activity
public void updateTextView(int count) {
// enter your code here to set the count in the textview
}
and from the baseAdapter call the above method like this:
if(mContext != null) {
((YourActivity)mContext).updateTextView(mCount);
}
and the textview in the activity will be updated!
I hope it helps.
In your OnItemClickListener call adapter.getItem(int position) to retrieve the object from the collection backing your BaseAdapter. From there, you should be able to retrieve any fields you need.
Edit:
Your edit clears up the question. Updated answer:
private int mCounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ListView listView = getYourListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCounter++;
updateTextView();
}
});
if(savedInstanceState != null) {
mCounter = savedInstanceState.getInt("counter", 0);
}
updateTextView();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", mCounter);
}
private void updateTextView() {
// TextView textView = getYourTextView();
textView.setText(String.valueOf(mCounter));
}
Just OnItemClickListener in your ListView then in the onClick you will get a value arg2 which is the position of the item which is clicked.
Just get that value from the ArrayList from which you are displaying the ListView and show it...
Hope this is what you need if I have not misunderstood your question.
try this code
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String itemText=(String) arg0.getItemAtPosition(arg2);
yourLable.setText(itemText);
}
});
In onListItemClick call list.getItemAtPosition(position) to retrieve item text
then set this text to textview1.setText(listText).
First Implement your onItemClickListener, where you will get int arg2 parameter, which is position, so get that position and do your stuff whatever you want like below.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
LABLE.setText(""+arg2);
}
});
Check this code
public class ListA extends ListActivity {
private TextView selection;
private static final String[] items={"Item 1", "Item 2", "Item 3"};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
selection=(TextView)findViewById(R.id.selection);
}
#Override
public void onListItemClick(ListView parent, View v, int position,
long id) {
selection.setText(position);
}
}
My current problem is I have a ListView I'm using to display my contacts now I'd like to set the onItemClick to grab the name of the contact and set that to a TextView called p2 the code I currently have is:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setp2);
cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
String[] from = new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
int[] to = new int[]{R.id.id_text,R.id.name_text};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(setp2.this,R.layout.setp2_layout,cursor,from,to);
ListView list = (ListView)findViewById(R.id.contact_list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
}
So basically I'm unsure of what I need to do in the onItemClick, any help appreciated!
In your onItemClick, you will get the instance of the view associated with that list item.From that view you can get the text associated with it and set it to the p2 TextView. If my understanding of your requirement is correct, the code will be something like this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
CharSequence name = ((TextView)view.findViewById(R.id.name_text)).getText();
//Set this to your textview in P2
tvP2.setText(name);
}
});
Set up a SimpleCursorAdapter.CursorToStringConverter and set it on the adapter, then use convertToString(Cursor cursor) to get the text in on item click :
(Cursor) simple.getItem(position)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
p2.setText(name);
}
});
I have an AutoCompleteTextView in my app which works. I have successfully created an onClickItemListener. The question is how to grab the text the user selected.
And this is the thing: I have an ArrayList with words being passed to the Adapter to search for suggestions. As the user types a word the suggestions list gets shorter (in rows on the UI side) so when i want to get the word from the ArrayList at the index the user selected i get the wrong word because the indexes doesn't match.
How can I get the text (String) the user chose without having to mess with the index?
Here's my code:
public class AutocompleteActivity extends BaseActivity {
private DBManager m_db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete);
m_db = new DBManager(this);
final ArrayList<String> words = m_db.selectAllWords();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, words);
AutoCompleteTextView tv = (AutoCompleteTextView)findViewById(R.id.autocomplete);
tv.setThreshold(1);
tv.setAdapter(adapter);
tv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.i("SELECTED TEXT WAS------->", words.get(arg2));
}
});
}
}
Yeah... unfortunately the name of the parameters on the onItemClick method you must implement are not so self-descriptive but here is an example with the names of what they are:
autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String)parent.getItemAtPosition(position);
//TODO Do something with the selected text
}
});
parent The AdapterView where the click happened.
view The view within
the AdapterView that was clicked (this will be a view provided by the
adapter)
position The position of the view in the adapter
id The row id of the item that was clicked.
For more info see: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
arg0 being your AdapterView and arg2 the position.
Have you tried:
arg0.getItemAtPosition(arg2);
I think what you are looking for is this.
String s = this.mCountry.getEditableText().toString();
Where mCountry is the AutoCompleteTextView.
this.mCountry = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
ArrayAdapter<String> adapterCountry = new ArrayAdapter<String>(this, R.layout.list_item, countries);
this.mCountry.setAdapter(adapterCountry);
mCountry is the list of countries, and I wanted to save the country selected in SharedPreferences.
Hope this helps.
Easiest of all
For Getting text of the selected suggestion in AutoCompleteTextView use this
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("========>>", autoCompleteTextView.getText().toString());
}
});
try this:
txtPurpose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Purpose selected = (Purpose) arg0.getAdapter().getItem(arg2);
txtPurpose.setTag(selected);
}
});
One another of getting text of suggestion selected in AutoCompleteTextView is
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView txtvw=(TextView) view;
String str=txtvw.getText().toString();
int index = contactNames.indexOf(str);
}
Here is the code that will solve the problem.
private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int index = (int) view.getTag();
Object item = parent.getItemAtPosition(index);
if (item instanceof SearchItemShareConnectionDAO) {
SearchItemShareConnectionDAO dao = (SearchItemShareConnectionDAO) item;
}
}
};
SetTag(Dao.getPosition) in getView() method of adapter.
To get the text of the displayed item selected by the user
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selectedItemText = arg0.getItemAtPosition(arg2);
Log.i("myTag", "SELECTED TEXT WAS["+selectedItemText+"]);
}
Following best practices, please use some form of descriptive nomenclature for your variables, your code will make more sense:
public void onItemClick(AdapterView<?> adapterViewIn, View viewIn, int selectedItemIndexIn, long id)
There is also a way to get item outside the onItemClick:
int index = tv.getListSelection();
if (index != ListView.INVALID_POSITION) {
Object item = tv.getAdapter().getItem(index);
}
beware that int getListSelection() may return ListView.INVALID_POSITION if there is no dropdown or if there is no selection.
For me, but on setOnItemSelectedListener():
arg0.getSelectedItem();
was enough. The same should work on setOnItemClickListener() I guess.
Kotlin version
autoCompleteId.setOnItemClickListener { parent, view, position, id ->
val selectedItem = parent.getItemAtPosition(position).toString()
Log.d("SELECTED ITEM", selectedItem )
}
Output:
D/CLASSROOM: selectedItem