I'm rather new to Android. Here's part of code:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Note selectedName = adapter.getItem(position);
adapter.removeItem(selectedName);
As you see, position means selected item position. That's good. But I'd prefer long clicks:
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.ctxmemu_delete:
** I need to use POSITION mentioned above! **
But in this method getSelectedItemPosition returns position -9995845834585 (or smth like that)
Or it gives error (can't move cursor to position - I use SQL in my app)
How can I get position from list properly?
P.S. sorry for my bad English :(
UPD:
I've added this to my SQL Adapter:
public int getPosition(){
return cursor.getPosition(); }
and modified:
case R.id.ctxmemu_delete:
int position = adapter.getPosition();
Note seln = adapter.getItem(position);
adapter.removeItem(seln);
return true;
for now it works...but I think it's so ugly...
You just need to use onListItemLongClick() instead of onListItemClick().
Why don't you use a onListItemLongClick listener instead of going for the context menu ?
protected void onListItemLongClick(ListView l, View v, int position, long id) {
super.onListItemLongClick(l, v, position, id);
Note selectedName = adapter.getItem(position);
adapter.removeItem(selectedName);
}
public boolean onContextItemSelected(MenuItem item) { ... }
Since you are using ContextMenu this is a little different from ItemClickListener
You can use MenuInfo for getting position in ListView
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Where it has int property info.position that returns position in the adapter for which the context menu was displayed.
Note: You can also have look at OnItemLongClickListener with works similar.
Related
guys what's up?
I'm still new to android and creating some testing app.
I have two Lists in my view. (Left and Right).
List Filled with values.
I trying to add selected list item value to other lists.
For example, If I clicked on an item in a left list. I wanna add selected item to Right list,
implemented OnItemClickListener into my code and OnItemClickListener onItemClick method is firing for both lists.
Any way to identify clicked list in an onItemClick method?
any suggestions are greatly appreciated.
After reading official API. Found a solution.
We can get the ID on the selected list.
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(adapterView.getId() == R.id.leftList){
// It's a left list
}else{
// It's a Right list
}
}
I'm not sure if I understand your question, but if you are trying to identify which list was clicked, you can call getId on the view in onItemCLick:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch (parent.getId()){
case R.id.left_list:
...
break;
case R.id.right_list:
...
break;
}
}
I have to remove the single item from list view in android while clicking long click. Please let me suitable code for removing a item in list view?
Here is the my code
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto - generated method stub
}
}
Use remove() method in your ArrayAdapter.
yourarrayAdapter.remove(yourarrayAdapter.getItem([POSITION]));
OR
yourarrayList.remove([POSITION]);
yourarrayAdapter.notifyDataSetChanged();
Try this in your click callback, to remove the view from its parent:
((ViewManager) parent).removeView(view);
I have a list of items.
I want to delete an item in a long push.
I saw this post and it worked for me.
just out of curiosity i wonder why other solution didn't work for me:
sol 1
I register the list to context menu:
registerForContextMenu(listView);
and then:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId()==R.id.comments_list) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.phone_list_contextual_menu, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit: {
return true;
}
case R.id.delete: {
comments.remove(info.id);
listView.invalidate();
return true;
}
default: {
return super.onContextItemSelected(item);
}
}
}
Is there a difference between
listView.invalidate() and adapter.notifyDataHasChanged() ? beside the subject of the call?
what am I missing in order for the remove to work?
sol 2
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
int position = (int) v.getTag();
comments.remove(position);
listView.invalidate();
return true;
}
});
instead of
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
comments.remove(pos);
//listView.invalidate();
arrayAdapter.notifyDataSetChanged();
return true;
}
});
I understand setOnItemLongClickListener is more suitable for my need than setOnLongClickListener but yet
why didn't this worked for me?
Is there a difference between
listView.invalidate() and adapter.notifyDataHasChanged() ? beside the subject of the call?
To my understanding adapter.notifyDataHasChanged() will do what listView.invalidate() plus more. That means it will also include change in number of items, and possibly inform other observers of data change. Relevant code is here:
http://androidxref.com/5.0.0_r2/xref/frameworks/base/core/java/android/widget/AdapterView.java#798
this is for notifyDataHasChanged(), as you can see mItemCount is udpated with new value. This means if you add more items to your arrayadapter, then invalidate, or better invalidateViews will not show them, at least at the end of list. One thing I have noticed is that above code has no invalidate call - maybe its called by some other methods.
Below is source code for invalidateViews (which is I think more proper than Invalidate):
http://androidxref.com/5.0.0_r2/xref/frameworks/base/core/java/android/widget/AbsListView.java#5078
It has no code to update count of item.
If you search source code for android sources, you will find only few cases when invalidateViews is called, some of those places are optimization hacks.
The difference is that invalidate causes all your views in the list to be scrapped and redrawn. Note I said views so that is what you are actually seeing on the screen (for example you can have 3 views on screen but 20 items in your list)
notifyDataHasChanged on the other hand tells the adapter that the contents have changed and the adapter needs to re-run its methods on the content to refresh the list.
You almost always want to use notifyDataHasChanged but it depends on exactly what you are trying to accomplish.
Hope that helps.
I have a problem. In my activity i have a ListView whose values are compiled from a Database. The database returns three columns: _Id, AccountName and Comments. What i want is that the when the user clicks on one of the items in the listView, that Item's position will be extracted and then that position will be compared with the postion in the ArrayList which has the data and then when the specific field and row is found out, the _Id field will be taken out and passed to another activity in the form of a String.
You may not have understood much; this might help:
public void search(View view){
final ListView vLst_IDCommName=(ListView)findViewById(R.id.lst_IDCommName);
EditText vTxt_searchTxt=(EditText)findViewById(R.id.search_txt);
String srch_str= vTxt_searchTxt.getText().toString();
if(srch_str.length()>0){
//The DataSource for the LstView
List<Comment> values = datasource.getContacts(srch_str);
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
vLst_IDCommName.setAdapter(adapter);
}
else{
Toast.makeText(getBaseContext(), "Please type in a value to proceed!", Toast.LENGTH_LONG).show();
}
vLst_IDCommName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Here I want to create a function that will take the position of the item clicked
//and then searched for that position in the ArrayList and then return the _Id of
//the account whose value was clicked.
}});
}
This code I used to get data:
public List<Comment> getContacts(String search_str) {
List<Comment> comments = new ArrayList<Comment>();
String srch_str=(String) search_str;
Cursor cur_comments= database.rawQuery("Select * from comments where acc_name like('%"+srch_str+"%')"+" "+ "or comment like('%"+srch_str+"%')", null);
cur_comments.moveToFirst();
while (!cur_comments.isAfterLast()) {
Comment comment = cursorToComment(cur_comments);
comments.add(comment); cur_comments.moveToNext();
}
cur_comments.close();
return comments;
}
Any feedback would be appreciated.
you can try
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String currentId=yourArrayList.get(position).toString();
}
vLst_IDCommName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Object s=parent.getItemAtPosition(position);
String j=s.toString();
}});
I have a simple array of Strings that I was displaying in a horizontal ListView with an ArrayAdapter. What I'm looking to do is: when the user selects an item from the ListView, make that item not clickable and change the background color of that item. Perhaps like a "grayed-out" look to it. I was looking into creating a custom Adapter and overriding the isEnabled(int position) method but I don't know how I would go about this. Any advice, suggestions, or help will be greatly appreciated thanks!
I was looking into creating a custom Adapter and overriding the isEnabled(int position) method but I don't know how I would go about this.
This is quite easy to do. I recommend a SparseBooleanArray to track the enabled items for efficiency:
public class MyAdapter extends ArrayAdapter<String> {
private SparseBooleanArray enabledItems = new SparseBooleanArray();
public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return enabledItems.get(position, true);
}
public void toggleItem(int position) {
boolean state = enabledItems.get(position, true);
enabledItems.put(position, !state);
}
}
The AutoComplete feature of Eclipse did must of the work, but here are some quick notes:
You must override areAllItemsEnabled() along with isEnabled()
I designed toggle() to be used by an onItemClickListener() you only need to call adapter.toggle(position)
If you want to change the row's appearance (more than what enabling and disabling does by default) simply override getView(). Don't forget to cover both cases:
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
if(!isEnabled(position)) {
/* change to disabled appearance */
}
else {
/* restore default appearance */
}
return convertView;
}
Hope that helps!
pass position to adapter class when you click on list item
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
adapter.setSelectedIndex(position);
}
add method of setSelectedIndex to adapter class
public void setSelectedIndex(int ind)
{
selectedIndex = ind;
notifyDataSetChanged();
}
Now check the postion of this listview if same then enable and disable value in getView me method
if(selectedIndex!= -1 && position == selectedIndex)
{
holder.tv.setBackgroundColor(Color.BLACK);
}
else
{
holder.tv.setBackgroundColor(selectedColor);
}
holder.tv.setText("" + (position + 1) + " " + testList.get(position).getTestText());
Reference from here
Use setEnabled(bool) property:
yourlistview.setEnabled(false);
Not sure whether it will work or not
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// your code
view.setBackgroundColor(Color.BLUE);
view.setEnabled(false);
}