I have a custom ListView with two button and I when I click either button on any row I want to get the text label on the Listview and for now just popup a toast with it. So far
Set onClick="click" to xml of button/image/etc...
and in your Activity, do:
public void click(View v) {
final int position = getListView().getPositionForView(v);
String text = getListView().getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext, text, Toast.LENGTH_SHORT).show();
}
simply use getItem() and pass the position
Ex:getItem(position).getID()
here getID() method is getter method
If you have a ListActivity, and you're not using your own adapter, you can still get the list item belonging to the tapped button, like so:
In your layout file of the list row:
<ImageButton
android:id="@+id/button_call"
android:layout_height="48dip"
android:layout_width="48dip"
android:contentDescription="Call"
android:onClick="callBuddy"
android:src="@drawable/call_button_image"
/>
In your ListActivity:
public void callBuddy(View view) {
int position = getListView().getPositionForView((View) view.getParent());
Buddy buddyToCall = (Buddy) getListView().getItemAtPosition(position);
Toast.makeText(MyListActivity.this, String.format("Calling your buddy %s.", buddyToCall.name), Toast.LENGTH_SHORT).show();
}
Easy to do:
call.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout rl = (RelativeLayout)v.getParent();
TextView tv = (TextView)rl.findViewById(R.id.label);
String text = tv.getText().toString();
Toast.makeText(CustomListView.this, text, Toast.LENGTH_SHORT).show();
}
});
use setTag attribute of the View..............
as
Button call = (Button) rowView.findViewById(R.id.button1);
call.setTag(position);
and
call.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int which = -1;
Obejct obj = v.getTag();
if(obj instaceof Integer){
which = ((Integer)obj).intValue();
}
if(which >-1){
String name = values[which];
Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
}
}
});