Making a custom android ListView adapter Clickable - android

I've been trying to create a clickable listview that takes in a string array and a few images and presents them in a textview style. So far I have managed to create a listview with each of the strings and images, however I am unsure how to use the onClick method so as to make the textviews clickable to start new activities etc.
Here is my code so far (Excluding XML):
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.activity_test2, values);
this.context = context;
this.values = values;
}
/* Print a toast when a list item is clicked, don't know what to do */
public void onClick() {
switch (list item) {
case 0:
Toast.makeText(this.context, "Pressed!", Toast.LENGTH_LONG).show()
break;
}
case 1:
etc....
}
#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_test2, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
String s = values[position];
if (s.startsWith("Report a Road Delay")) {
imageView.setImageResource(R.drawable.ic_menu_compose);
} else if (s.startsWith("View Reported Delays")) {
imageView.setImageResource(R.drawable.ic_menu_view);
} else if (s.startsWith("Search a Road for Delays")) {
imageView.setImageResource(R.drawable.ic_menu_search);
} else if (s.startsWith("Update a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_edit);
} else if (s.startsWith("Validate a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_mark);
}
return rowView;
}
}
public class MainActivity extends ListActivity {
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
String[] values = new String[] { "Report a Road Delay",
"View Reported Delays", "Search a Road for Delays",
"Update a Delay Report", "Validate a Delay Report" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
}
}
This is how it looks so far:
All I basically don't understand is the onClick method; what parameters it takes it, and how to determine which item was clicked. Any help would be appreciated.

Try this:
ListView list1 = getListView();
list1.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//Take action here.
}
}
);

You are looking for an OnItemClickListener and not an OnClickListener
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// DO SOMETHING WITH CICK EVENT HERE
}
}
Now only to discus the params:
parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked
position The position of the view in the adapter.
id The row id of the item that was clicked.
I got the last part from android reference

You could use this code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a <extView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
// we register for the contextmneu
registerForContextMenu(lv);
}
where lv is the listView.
If you want to add a context menu:
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
Planet planet = aAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + planet.getName());
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
planetsList.remove(aInfo.position);
aAdpt.notifyDataSetChanged();
return true;
}
If you want to have more information give a look on my blog here and here

Related

Select listview item on second click

The code populates the listview with items using baseadapter. On clicking on the item it changes background color and goes to the next activity. Now i want to change the back ground color on first click and it should stay selected. Then on next click it should go to the next activity. Is it possible to do so.
Activity
nameList = (ListView) findViewById(R.id.list_names);
nameList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
nameList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId)
{
TextView PCNtv = (TextView) view.findViewById(R.id.value_Name);
String P_Name = PCNtv.getText().toString();
Intent intents = new Intent(getApplicationContext(), Activity2.class);
intents.putExtra("P_Name", P_Name);
view.setSelected(true);
startActivity(intents);
}
});
In drawable
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/blue_color"/>
<item android:state_pressed="true" android:drawable="#drawable/white_color"/>
<item android:state_focused="true" android:drawable="#drawable/red_color"/>
</selector>
Use the views selected property to detect the second click. First click will select the view, the second will open the activity.
nameList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId)
{
TextView PCNtv = (TextView) view.findViewById(R.id.value_Name);
String P_Name = PCNtv.getText().toString();
if ( view.isSelected() ) {
Intent intents = new Intent(getApplicationContext(), Activity2.class);
intents.putExtra("P_Name", P_Name);
startActivity(intents);
}
view.setSelected(true);
});
}
Update
The selection is lost when the users presses the view again, so the code above does not work. Here is a solution involving the adapter tracking the currently selected position.
The click event:
nameList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Check to see which item in the adapter is already
// selected, if the same has been selected twice, start new activity
if ( i == ((TestAdapter)adapter).getSelectedIndex()) {
// Start your new activity here.
Log.d("TAG", "second push");
}
((TestAdapter)adapter).setSelectedIndex(i);
}
});
You did not show the code for your adapter, so here is a simple one with the selected index added:
public class TestAdapter extends ArrayAdapter<String> {
private final Activity context;
private int mSelection = -1;
public TestAdapter(Activity context, String[] objects) {
super(context, R.layout.text_layout, objects);
this.context = context;
}
// Call this when an item is clicked, this sets the
// internal index for the selected item and notifies the view
// that the data has changes, this will force the view to draw
// allowing it to correctly highlight the selected item
public void setSelectedIndex(int index) {
mSelection = index;
notifyDataSetChanged();
}
// This is needed for the click listener to check to see which
// item is already selected
public int getSelectedIndex() {
return mSelection;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.text_layout, null);
TextView tv = (TextView)rowView.findViewById(R.id.text3);
tv.setText(getItem(position));
// Adds or removes the selection on the view so
// it will display as selected
if ( mSelection == position ) {
tv.setSelected(true);
} else {
tv.setSelected(false);
}
return rowView;
}
}
Updated: added inline comments

How to delete a row from a ListView with a CursorAdapter

I started a small Android project to re-learn a bit of Android development, and I'm already stuck...
I do not know how to implement the deletetion of an element of my ListView!
Here is the project: https://github.com/gdurelle/Listify
Right now it aims at showing a list of lists of elements.
I use a custom CursorAdapter to show my list of elements, and I already have a (ugly) destroy button, but I do not know how to make it delete an actual element from the list (and the database).
I use ActiveAndroid to manage the database in the ActiveRecord way.
Plus: I'm not sure wether or not to use getView(), bindView(), and/or newView()...
I created an issue to remember this and reference this question here: https://github.com/gdurelle/Listify/issues/1
public class ListifyCursorAdapter extends CursorAdapter {
public String content;
public ListifyCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it, you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.element_line, parent, false);
}
// The bindView method is used to bind all data to a given view such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
}
And in my MainActivity :
Cursor cursor = ListifyElement.fetchResultCursor();
adapter = new ListifyCursorAdapter(this, cursor);
listView.setAdapter(adapter);
I was thinking maybe about a:
Button delete_button = (Button) listView.findViewById(R.id.delete_button);
with something like ListifyElement.load(ListifyElement.class, the_id_of_the_element).delete(); where the_id_of_the_element would be the DB's id of the element retrieived somehow from the click on it's delete_button in the UI...
UPDATE:
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(cursor.getColumnName(0)); // Id
System.out.println(cursor.getColumnName(1)); // ListifyContainer
System.out.println(cursor.getColumnName(2)); // content
System.out.println(cursor.getColumnIndexOrThrow("Id")); // 0
ListifyElement.load(ListifyElement.class, cursor.getColumnIndexOrThrow("Id")).delete();
notifyDataSetChanged();
}
});
I get this error when I click the delete button:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gdurelle.listify.models.ListifyElement.delete()' on a null object reference
If you want a Button in each row, you should add it to your xml which you inflate in the newView(). After that, you should set OnClickListener to your Button inside bindView(). Something like that:
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//As you're using ActiveAndroid
new Delete().from(ListfyElement.class).where("yourCondition=?",yourCondition).execute();
notifyDataSetChanged();
}
});
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
Use below code to perform this--
ListView lv;
ArrayList<String> arr = new ArrayList<String>();
ArrayAdapter adapter;
int position;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.extra);
for(int i=0;i<5;i++)arr.add("Hi # "+i);
lv = (ListView) findViewById(R.id.listViewBirthday);
lv.setOnItemLongClickListener(this);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, arr);
lv.setAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuItem it1=menu.add("Delete");
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int p, long arg3)
{
position = p;
registerForContextMenu(lv);
return false;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getTitle().equals("Delete"))
{
arr.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "deleted", Toast.LENGTH_SHORT).show();
}
return true;
}
The context menu is relatively simple to implement on a listview. It (context menu) is activated on a long press of the item. My tip is to add an intent to the menu item so you can preserve the item id from your custom adapter and use it to perform whatever you want.
public class MainActionBarTabListFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
registerForContextMenu(getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String name = adapter2.getItem(info.position).get_name();
menu.setHeaderTitle(name);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menulistitem, menu);
MenuItem mi = menu.findItem(R.id.action_context_delete);
Intent i = new Intent();
i.putExtra("id", adapter2.getItem(info.position).get_id());
mi.setIntent(i);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_context_delete:
Intent i = item.getIntent();
if (i != null) {
Bundle b = i.getExtras();
if (b != null) {
int id = b.getInt("id");
Uri deleteIdUri = ContentUris.withAppendedId(
RidesDatabaseProvider.CONTENT_URI, id);
context.getContentResolver()
.delete(deleteIdUri, null, null);
return true;
}
}
}
return super.onContextItemSelected(item);
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_context_delete"
android:icon="#drawable/action_about"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:title="delete"
yourapp:showAsAction="ifRoom"/>
</menu>
lets start from the beginning, why do you need to use ActiveAndroid? I suggest to avoid such things, IMHO. You've mixed your logic, adapter should not change your database. Set a listener to adapter (i.e. IDeleteListener with single method onDeleteRequested(long rowId)). Next you need to pass rowId, something like:
delete_button.setTag(cursor.getLong(0));
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
listener.onDeleteRequested((Long)v.getTag());
}
});
In your fragment/activity class you should set a listener to adapter and work with your database. I suggest you to use LoaderManager this will automatically re-query your db on delete and handle life cycle of activity.
Hope that helps!
I would suggest you to use an ArrayAdapter instead. Then you are just using an ArrayList (or any other array) and edit it, and call adapter.notifyDataSetChanged();, and the content of the ListView will update.
Declare the ArrayAdapter like this:
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
where the variable called yourStringArray is just an ArrayListof Strings.
Then, add the adapter to the ListView, like this:
yourListView.setAdapter(adapter);
Then, you can modify the contents of the list, by editing the yourStringArray list, and calling adapter.notifyDataSetChanged();. Here is a simple example:
list.add("Hello!");
adapter.notifyDataSetChanged();
Finally, to remove the selected item when the button is clicked, you can do something like this:
int selectedItemIndex = 0;
yourArrayList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
The whole onCreate method would look something like this:
// Called when the activity is created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> yourStringArray = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
int selectedItemIndex = 0;
ListView yourListView = (ListView) findViewById(R.layout.yourListViewID);
yourListView.setAdapter(adapter);
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
}

Getting listview item index in android

I am making an android application that uses a listview. I want to get the index number of an item once an item has been pressed(single-click). I've gone through several tutorials, but none seemed to help. How can i get the index number and pass it to a String. I do then want to delete it, but i'll manage that part my self. I only need the index number and pass it to a string. The code where i'll get the index number is straigt after the onCreate method. Please help and thanks in advance! This is the code that i am using:
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout;
public String DeleteIndexNumber;
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));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
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();
//This is where i need the index number to be passed to the string "DeleteIndexNumber"
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#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:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
break;
}
}
}
notice the parameters for the onItemClick method
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
position will give you the index you desire..
Isn't it position parameter in onItemClick ?
The position parameter in onItemClick will give you the index of the clicked Item in the list.

BaseAdapter and ContextMenu

Hello stackoverflow community,
Basically, i have gallery displaying some images using a gridView + imageView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<GridView android:id="#+id/PhoneImageGrid"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:numColumns="auto_fit" android:verticalSpacing="12dp"
android:horizontalSpacing="12dp" android:columnWidth="90dp"
android:stretchMode="columnWidth" android:gravity="center" />
<ImageView android:id="#+id/thumbImage" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true"
android:scaleType="centerCrop"
/>
I would like to use setOnLongClick for each imageView displayed by the adapter.
This works well, however, when clicking long on the imageView, i would like to display a ContextMenu with some items ( i.e, you long click on an imageView, a contextMenu is displayed with some items : Image information, send this image ...).
Unfortunatly, i can't figure out how to inflate this menu in the adapter.(Probably not the good way to do it )
I have the following lines in my main activity
_adapter = new ImageAdapter(activity,storedObjects.getAlbums());
imagegrid.setAdapter(_adapter);
My adapter ( some useless lines removed )
public class ImageAdapter extends BaseAdapter {
private Albums albums;
private Context context;
private LayoutInflater inflater;
public ImageAdapter(Context context, Albums albums) {
this.albums = albums;
this.context = context;
inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
if(albums.getAlbumsListSize() == 0) {
Toast.makeText(context, "There is no album to display", Toast.LENGTH_LONG).show();
}
}
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) view.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) view.findViewById(R.id.itemCheckBox);
holder.textview = (TextView) view.findViewById(R.id.album_name);
holder.checkbox.setChecked(true);
//Bitmap loadingBM = BitmapFactory.decodeResource(context.getResources(),R.drawable.loading_image);
//holder.imageview.setImageBitmap(loadingBM);
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
}
holder.imageview.setClickable(true);
holder.imageview.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
Log.v(TAG,"onLongClick ok !");
return false;
}
});
imageDownloader.download(this.context, albums.getAllAlbums().get(position).getThumbnailUri(), holder.imageview);
return view;
}
Questions :
setOnLongClickListener works properly, when i click on an image, my Log is displayed in logcat, however, how to create a menu for each imageView ?
Apparently, i can only override onCreateContextMenu in my main activity. I guess i could pass each ImageView to onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) but how ?
I would be really grateful if you could help me out with this.
Thank you very much
Florent Valdelievre
Instead of setOnLongClickListener on the ImageView, call registerForContextMenu with your GridView. Then, implement onCreateContextMenu and onContextItemSelected.
Here is a simple ListActivity to show you how it works.
public class GreetingActivity extends ListActivity {
private static final String[] mGreetings = { "Hello", "Goodbye" };
private static final String[] mPeople = { "Alice", "Bob", "Charlie" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mPeople);
setListAdapter(adapter);
ListView listView = getListView();
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
for (int i = 0; i < mGreetings.length; ++i) {
String greeting = mGreetings[i];
menu.add(v.getId(), i, ContextMenu.NONE, "Say " + greeting);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo
= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int adapterPosition = menuInfo.position;
String person = mPeople[adapterPosition];
int menuItemId = item.getItemId();
String greeting = mGreetings[menuItemId];
String msg = String.format("%s, %s!", greeting, person);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
return true;
}
}
Thank you so much #chiuki, it works as expected
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
final GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
registerForContextMenu(imagegrid);
storedObjects.storeThumbnailsURI();
_adapter = new ImageAdapter(activity,storedObjects.getAlbums());
imagegrid.setAdapter(_adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Log.v("context menu","context menu");
menu.setHeaderTitle("Context Menu");
menu.add(0, START_SLIDESHOW_ON_THIS_ALBUM, 0, "Start SlideShow for this Album");
menu.add(0, DOWNLOAD_WHOLE_ALBUM, 0, "Download this Album");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case START_SLIDESHOW_ON_THIS_ALBUM:
selectThisAlbumOnly(info);
startSlideShow();
break;
case DOWNLOAD_WHOLE_ALBUM:
break;
}
return true;
}
In the Adapter, make sure you don't have any setClickable = true
Cheers
Florent

Need Help ListView and onItemClickListener

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.

Categories

Resources