where to perform onClickListener and how?
-
16-04-2021 - |
Domanda
I have an activity which have a button and a listview(with chechbox, image and text).
I am Making the listview from the customAdapter class which extends the BaseAdapter
class.
I am handling checkboxes in that customAdapter class.
Now my problem is that how to know that which item is checked and how to perform action on
that checked listItems.Because my button is in the activity but i need to perfom that onClickListener
in that customadapter class
??
Thanks for help.
Soluzione
You would put the Button click listener inside of your GetView() method, where you inflate the view for each row in your list.
For the checkbox items you would do the same..it would look something like this in your getview()
CheckBox cbx = (CheckBox)view.findViewById(R.id.c_checkbox);
if(cbx.isChecked()){
Toast.makeText(getApplicationContext(),
"Checked position " + position,
Toast.LENGTH_SHORT).show();
}
Altri suggerimenti
You could use a custom-made OnItemClickListener
that implements OnClickListener
.
private class CustomAdapter extends BaseAdapter implements OnClickListener {
public MyAdapter() {
/* Your constructor */
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row, null);
}
// take the CheckBox and set the listener.
CheckBox cbx = (CheckBox) convertView.findViewById(R.id.checkbox);
cbx.setOnClickListener(this);
// set the listener for the whole row.
convertView.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
@Override
public void onClick(View v) {
Log.v(TAG, "Row button clicked");
}
}
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
@Override
public void onClick(View v) {
Log.v(TAG, "onItemClick at position" + mPosition);
}
}
}
Also note that putting a focusable view in a list item prevents the firing of onListItemClick() when the list item is clicked.
Hope this helps.