I have a custom view for each row in a custom ListAdapter and I am trying to perform onClick action and get the row position in the list where the click came from.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingLeft="10dip" android:id="#+id/itemRoot" android:clickable="false">
<TextView android:layout_width="wrap_content" android:text="TextView"
android:layout_height="wrap_content" android:id="#+id/itemTxt"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"></TextView>
<TextView android:layout_toRightOf="#+id/itemTxt" android:text="TextView"
android:layout_height="wrap_content" android:layout_alignBottom="#+id/itemTxt"
android:id="#+id/amountTxt" android:paddingLeft="6dip"
android:layout_centerVertical="true" android:layout_width="match_parent"></TextView>
<ImageView android:id="#+id/delBtn" android:layout_height="wrap_content"
android:src="#drawable/delete" android:layout_width="wrap_content"
android:layout_alignParentRight="true" android:paddingRight="10dip"
android:layout_centerVertical="true"></ImageView>
</RelativeLayout>
I want to figure out when TextView or ImageView is clicked, I also need to know what row in the list it came form. I have tried using OnItemClickListener and it works fine to get the row where the click comes from. However, once I register an OnClick listener for the views, the onItemClicked() method gets skipped and onClick() is executed straight away, but there is no way of getting the row position that the view is in(or at least not that I know if).
If I set clickable to false for the views, then onItemClicked get called and I tried manually calling performClick() on the given view. But this only works for the root element (RelativeLayout), and if click comes from TextView inside the layout the click doesn't propagate.
I can't really figure out how to get both position in the list and perform onClick action.
Any thoughts are welcome.
Alex
You could assign the proper OnClickListener to each ImageView and TextView from inside your ListAdapter's overridden getView method.
Inside that method you know the item's position, so you can pass it to the custom listener classes, and use it there as you want:
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO: instantiate the layout
// here I call a super method
final View view = super.getView(position, convertView, parent);
final TextView textView = (TextView)view.findViewById(R.id.itemTxt);
textView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.i("Click", "TextView clicked on row " + position);
}
});
final ImageView imageView = (ImageView)view.findViewById(R.id.delBtn);
imageView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.i("Click", "ImageView clicked on row " + position);
}
});
return view;
}
The other possible option to have the OnClickListener in the same class as the creating activity is to add to the activity implements OnItemClickListener.
public class DisplayListCustom extends Activity implements OnItemClickListener
Then set the custom list to listen
ListView list = (ListView)findViewById(R.id.custom_list);
list.setClickable(true);
list.setOnItemClickListener(this);
list.setAdapter(new CustomListAdapter(getApplicationContext(), listItems));
Finally in the onItemClick return, you can find the inner views by using resource ID
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
LinearLayout listItem = (LinearLayout) v;
TextView clickedItemView = (TextView) listItem.findViewById(R.id.name);
String clickedItemString = clickedItemView.getText().toString();
Log.i("DisplayListCustom", "Click detected " + clickedItemString + ", position " + Integer.toString(position));
This is the solution I went with. I used LinearLayout for my custom layout container, but I assume the same applies to RelativeLayout.
You need to extend your TextView etc, override the click method, do the appropriate actions and then the trick is to return false so it's then propagated to the listview.
Related
I am trying to create an item in a ListView that has multiple options; view and edit. I would like to create it in exactly the same way as android's contact system - see below:
I have added the red boxes to illustrate the behaviour I want. If you press within the left red-box, you call the contact. If you press within the right red-box, you send a text message to the contact. I have already created a similar layout in XML, but I am having trouble implementing this functionality in code.
I have tried to create custom android:onClick function calls for the separate layouts within the item, but calling an onClick method only allows you to pass in the View as a parameter, but not the position. Needing the position to use listview.getItemAtPosition function, I tried to use listview.getPositionForView to return the position but found this was extremely unstable and was very easy to return incorrect positioning due to recycling of views.
I then tried to set the item's position as the 'tag' in the getView method of my adapter, like so: convertView.setTag(position). But on the onClick method of my activity, I try and use getTag and cast it back to an integer, and it always returns null, which I find puzzling.
What is the best way of implementing a list populated by items with multiple buttons/layouts on each item?
You can create an onClick event on each views in your row like this :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/text_id"
android:layout_width="0sp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical"
android:onClick="textOnClickEvent"/>
<ImageButton
android:id="#+id/button_id"
android:layout_width="#dimen/width_button"
android:layout_height="match_parent"
android:onClick="imageOnClickEvent"
android:src="#android:drawable/ic_menu_delete" />
</LinearLayout>
Or even, add onClick listeners on each views in the getView method...
more info on this here.
In the list view when you define getview method, this is where you provide all the details of the single list item. There you can mention onlick event of each of the views.
in adapter class, add View.OnClickListener to the getView method:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.grid_vendor_item, null);
}
final TextView textName = (TextView) view.findViewById(R.id.text_id);
final ImageButton imageProfil = (TextView) view.findViewById(R.id.button_id);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// add your edit codes
}
});
imageProfil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// add your open prodil codes
}
});
return view;
}
I use ListView to show several items.
My row.xml as below:
<TextView android:text="text"
android:id="#+id/tvViewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<Button android:text="Click me!"
android:id="#+id/BtnToClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClick">
</Button>
And I define myClick in Activity as below:
public void myClick (View v) {
LinearLayout vwParentRow = (LinearLayout)v.getParent();
//How to get the position
}
How to know the position which buttom be clicked?
The position mean same as the method onListItemClick's.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
}
Try
public void DetailClick(View v) {
ListView lv = getListView();
int position = lv.getPositionForView(v);
}
You can try like this.
Step 1: In your custom adapter
#Override
public view getView(int position, View convertView, ViewGroup parent){
.......//Perform your logic
convertView.findViewById(R.id.BtnToClick).setTag(position);
return convertView;
}
Step 2: In onclick listener
public void myClick (View v) {
LinearLayout vwParentRow = (LinearLayout)v.getParent();
position=(Integer) v.getTag();
}
Yes the position in the onListItemClick is same as the position of the item clicked in the list.
If I understand your question correctly, you have a button in each row of a ListView, and you want to know which row received the button click. How are you doing an setOnClickListener() on the button? The reason I ask this is - if you are setting the OnClickListener for each button, you already know the position of that button.
You should also read the documentation for ListView and even look through the available methods and their sample code.
Know your documentation.
I have a Gridview filled by an Adapter which returns LinearLayouts each contains an ImageButton and TextView.
In the adapter I am binding an onClick and onLongClick event to the ImageButton.
I am trying to bind OnItemClickListener to the gridview but I don't know why that the onItemclicked never fired up.
It's my 6th hour without anything.
By the way;
OnItemSelectListener working perfectly on the Grid.
I am checking if some piece of code accidentally handles the onItemClicked but couldn't catch yet.
I need help guys.
gridView = (GridView) layoutInflater.inflate(R.layout.gridview, null);
gridView.setOnItemClickListener(new ItemClickListener());
.
.
.
//inner handler class
class ItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(mainActivity.getApplicationContext(),view + " clicked at pos " +
i,Toast.LENGTH_SHORT).show();
}
}
Do not use clickable objects in the grid. In that case Android cannot handle the click event of GridView.
Instead, use something to show a similar user interface view. Then handle that object's click actions.
Don't: put Button in the GridView to perform some click actions.
Do: put an ImageView instead of ImageButton and handle ImageView's click events.
If you wants to use Button or ImageButton then you need to write these attributes in your xml code of the widgets.
android:focusable="false"
android:focusableInTouchMode="false"
Its works for me.
But in GridView, Try to avoid use of these widgets. You can use any other widgets in place of these (Like ImageView or any other).
Also make sure, that your ListAdpter returns true for
public boolean isEnabled(int _position)
for the position you want to click.
Hey guyz finally got a solution...
what we were doing is directly accessing the Layout inside the GridView, so the onItemClickListener finds it confusing to access the item.
So the solution is to apply the onClickListener inside the Adapter (i.e. normally ArrayAdapter)
so what i m trying to say is:
public View getView(int position, View convertView, ViewGroup parent) {
//Here row is a view and we can set OnClickListener on this
final View row;
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
//Here we inflate the layout to view (linear in my case)
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
row = convertView;
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
//Now get the id or whatever needed
row.setId(position);
// Now set the onClickListener
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "Clicked" + row.getId() + "!!",
Toast.LENGTH_SHORT).show();
}
});
return row;
}
Try to set
android:clickable="false"
android:focusable="false"
I meet same problem too, because of several reasons.
So, here's my tips:
Extend BaseAdapter for your adapter;
Use OnClickListener inside the getView in adapter instead setting OnItemClickListener for GridView;
Avoid setting LayoutParams multiple times;
Check if position = 0, don't use convertView, inflate new View;
Set OnClickListener not only for parent View, but for any child View, if any;
Make all your Views clickable.
I just tested it on 4 devices, and this solution works as expected. Hope, it will help in your case.
Correct me, if I made something wrong.
Layout code XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#273238"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:padding="1dp">
<ImageView
android:id="#+id/open_image_item_imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/loh"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/open_image_item_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_gravity="bottom"
android:padding="4dp"
android:textSize="10sp"
android:ellipsize="start"
android:background="#55000000"
android:textColor="#FFFFFF"
android:text="image name"/>
</FrameLayout>
Adapter code Java:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView != null && position != 0)
view = convertView;
else{
view = LayoutInflater.from(getContext()).inflate(R.layout.open_image_item_layout, null, false);
view.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, size));
}
TextView textView = (TextView)view.findViewById(R.id.open_image_item_textview);
ImageView imageView = (ImageView)view.findViewById(R.id.open_image_item_imageview);
...
View.OnClickListener onClickListener = getOnClickListener(files[position]);
view.setOnClickListener(onClickListener);
textView.setOnClickListener(onClickListener);
imageView.setOnClickListener(onClickListener);
return view;
}
I have a ListView with an ArrayList adapter. The rows are not very complex (an Image on the left, a LinearLayout with TextViews inside, and a CheckBox on the right ... the layout is copied in below.) The goal is to have a QuickAction bar come up if the user clicks on the image or text, and have the CheckBox change state if the user clicks on the CheckBox. I have each part working independently, but not when they're together in the layout - somehow, I'm losing the onItemClick event.
The "QuickAction" bar is activated by OnItemClickListener(), and it works fine - unless I have the CheckBox in the layout, in which case the CheckBox works fine (using onClick()) but the onItemClickListener is never fired if the user clicks in the row but outside the CheckBox. The layout (minus some style stuff) is:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vw1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView android:id="#+id/img"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<CheckBox android:id="#+id/ckb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:checked="false" />
<!-- stack text in middle section of the row -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content""/>
<TextView android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
The code behind it isn't complicated:
public class ListGroupsActivity extends BaseActivityForList {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// add QuickAction bar
ListView lv = getListView();
lv.setOnItemClickListener(new QAListener(this));
}
}
//inner classes of the ListGroupsActivity
class CbOnClickListener implements OnClickListener {
// ...
// test the checkbox isChecked() and keep state in 'selectedItems' array
class GroupListAdapter extends ArrayAdapter<Group> {
super(/*...*/)
CbOnClickListener cblistener = null; // common listener for all the CheckBoxes
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// here do normal testing for convertView being null etc
// heres the view inflation from the layout into the ViewHolder
holder.tv1 = (TextView) convertView.findViewById(R.id.text1);
holder.tv2 = (TextView) convertView.findViewById(R.id.text2);
holder.img = (ImageView) convertView.findViewById(R.id.img);
holder.ckb = (CheckBox) convertView.findViewById(R.id.ckb);
Group g = groups.get(position); // this is the data obj for the row
holder.tv1.setText(g.getName());
holder.tv2.setText("child groups");
Bitmap bm = BitmapFactory.decodeFile(g.getIconUri());
holder.img.setImageBitmap(bm);
Integer key = (Integer) g.getId();
holder.ckb.setChecked(selectedItems.contains(key));
holder.ckb.setOnClickListener(cblistener); // hook onClick to cblistener
return convertView;
}
The QAListener is in a superclass for all my list activities:
public class BaseActivityForList extends
OrmLiteBaseListActivity<DatabaseHelper> {
// QAListener inner class, constructs new quick action bar when item clicked
class QAListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// has three ActionItem instances, 'copyAction', 'delAction', 'editAction'
ActionItem copyAction = new ActionItem();
copyAction.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ... does some stuff
mQuickAction.dismiss();
}
}); // end setOnClickListener
} // end onItemClick
} // end QAListener
} end BaseActivityForList
So, how do I arrange for the Checkbox to pick up the onClick, and the rest of the list item to pick up the onItemClick()?
After few hours of debugging and research. I got it working by
setting following properties on the checkbox:
android:focusable="false"
android:focusableInTouchMode="false"
Also ImageView may need to be configured as described in http://blog.sachin.name/?p=62 (Thanks to that person)
On my side, I discovered that item view MUST NOT be clickable and text views should not be clickable, either. It took me a while to realize that I called setClickable(true) on my item view somewhere in the code.
Just for complementing this accepted answer: in case of ImageButton instead of CheckBox it is not enough to set in xml focusable and focusableInTouchMode to false but during runtime focusable need to be set to false. That means to make sure onItemClick will be detected one must do smth like:
button.setFocusable(false);
so things work completely.. Original credits to author here . hope it will help to someone.
Cheers ;)
Edit: There is even more elegant solution try to add android:descendantFocusability="blocksDescendants" in root layout of list element. That will make clicks onListItem possible and separately u can handle Button or ImageButton clicks
I have a simple ListActivity that uses a custom ListAdapter to generate the views in the list. Normally the ListAdapter would just fill the views with TextViews, but now I want to put a button there as well.
It is my understanding and experience however that putting a focusable view in the list item prevents the firing of onListItemClick() in the ListActivity when the list item is clicked. The button still functions normally within the list item, but when something besides the button is pressed, I want onListItemClick to be triggered.
How can I make this work?
as I wrote in previous comment solution is to setFocusable(false) on ImageButton.
There is even more elegant solution try to add android:descendantFocusability="blocksDescendants" in root layout of list element. That will make clicks onListItem possible and separately u can handle Button or ImageButton clicks
Hope it helps ;)
Cheers
I hope I can help here. I assume that you have custom layout for listView items, and this layout consists of button and some other views - like TextView, ImageView or whatever. Now you want to have different event fired on button click and different event fired on everything else clicked.
You can achieve that without using onListItemClick() of your ListActivity. Here is what you have to do:
You are using custom layout, so probably you are overriding getView() method from your custom adapter. The trick is to set the different listeners for your button and different for the whole view (your row). Take a look at the example:
private class MyAdapter extends ArrayAdapter<String> implements OnClickListener {
public MyAdapter(Context context, int resource, int textViewResourceId,
List<String> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String text = getItem(position);
if (null == convertView) {
convertView = mInflater.inflate(R.layout.custom_row, null);
}
//take the Button and set listener. It will be invoked when you click the button.
Button btn = (Button) convertView.findViewById(R.id.button);
btn.setOnClickListener(this);
//set the text... not important
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(text);
//!!! and this is the most important part: you are settin listener for the whole row
convertView.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View v) {
Log.v(TAG, "Row button clicked");
}
}
Your OnItemClickListener class could be declared like here:
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.v(TAG, "onItemClick at position" + mPosition);
}
}
Of course you will probably add some more parameters to OnItemClickListener constructor. And one important thing - implementation of getView shown above is pretty ugly, normally you should use ViewHolder pattern to avoid findViewById calls.. but you probably already know that.
My custom_row.xml file is RelativeLayout with Button of id "button", TextView of id "text" and ImageView of id "image" - just to make things clear.
Regards!
When a custom ListView contains focusable elements, onListItemClick won't work (I think it's the expected behavior). Just remove the focus from the custom view, it will do the trick:
For example:
public class ExtendedCheckBoxListView extends LinearLayout {
private TextView mText;
private CheckBox mCheckBox;
public ExtendedCheckBoxListView(Context context, ExtendedCheckBox aCheckBoxifiedText) {
super(context);
…
mText.setFocusable(false);
mText.setFocusableInTouchMode(false);
mCheckBox.setFocusable(false);
mCheckBox.setFocusableInTouchMode(false);
…
}
}
I have the same problem: OnListItemClick not fired ! [SOLVED]
That's happen on class that extend ListActivity,
with a layout for ListActivity that content TextBox and ListView nested into LinearLayout
and another layout for the rows (a CheckBox and TextBox nested into LineraLayout).
That's code:
res/layout/configpage.xml (main for ListActivity)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="pippo" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:background="#aaFFaa" >
</ListView>
<LinearLayout>
res/layout/row.xml (layout for single row)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
**android:focusable="false"**
**android:focusableInTouchMode="false"** />
<TextView
android:id="#+id/testo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
**android:focusable="false"**
**android:focusableInTouchMode="false"** />
</LinearLayout>
src/.../.../ConfigPage.java
public class ConfigPage extends ListActivity
{
TextView selection;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configpage);
// loaded from res/value/strings
String[] azioni = getResources().getStringArray(R.array.ACTIONS);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row,
R.id.testo, azioni));
selection = (TextView) findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View view, int position, long id)
{
selection.setText(" " + position);
}
}
This begin to work when I added on row.xml
android:focusable="false"
android:focusableInTouchMode="false"
I use Eclipse 3.5.2
Android SDK 10.0.1
min SDK version: 3
I hope this is helpful
... and sorry for my english :(
just add android:focusable="false" as one of the attributes of your button
I've had the same problem with ToggleButton. After half a day of banging my head against a wall I finally solved it.
It's as simple as making the focusable view un-focusable, using 'android:focusable'. You should also avoid playing with the focusability and clickability (I just made up words) of the list row, just leave them with the default value.
Of course, now that your focusable views in the list row are un-focusable, users using the keyboard might have problems, well, focusing them. It's not likely to be a problem, but just in case you want to write 100% flawless apps, you could use the onItemSelected event to make the elements of the selected row focusable and the elements of the previously selected row un-focusable.
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(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
I used the getListAdapter().getItem(position) instantiating an Object that holds my values within the item
MyPojo myPojo = getListAdapter().getItem(position);
then used the getter method from the myPojo it will call its proper values within the item .