public class ChooseFavorites extends Activity implements OnItemClickListener
{
StationManager st;
MyCustomAdapter arr;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_favorites);
st = new StationManager();
list = (ListView)findViewById(R.id.stationsList1);
arr = new MyCustomAdapter(this, android.R.layout.simple_list_item_multiple_choice, st.getNamesOfStations());
list.setAdapter(arr);
list.setOnItemClickListener(this);
}
class MyCustomAdapter extends ArrayAdapter<String> implements OnClickListener
{
LayoutInflater inflater;
Context ctx;
CheckBox cb;
String[] stationNames;
TextView stationName1;
public MyCustomAdapter(Context context, int textViewResourceId, String[] stationNames) {
super(context, textViewResourceId, textViewResourceId, stationNames);
ctx = context;
this.stationNames = stationNames;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 23;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return stationNames[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row = convertView;
if(row==null)
{ // Object reuse
inflater = getLayoutInflater();
row = inflater.inflate(R.layout.favorite_row, parent, false);
}
stationName1 = (TextView)row.findViewById(R.id.textFavoriteItemInRow);
stationName1.setText(stationNames[position]);
cb=(CheckBox)row.findViewById(R.id.cbCheck);
row.setOnClickListener(this);
return row;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "" + position, Toast.LENGTH_SHORT);
toast.show();
}
}
I don't know if you can see this only through code...
but If there were not an onClick in the class my costume adapter, nothing would have happen...
the android don't use the "on item click listener"
but it does work on the "on click" method....
the problem is : I DONT HAVE POSITION which I truly need...
hope anyone can help me about that! thank you all!
You can use this event to get notified about the checkbox being checked/unchecked
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
}
}
Use Checkbox setOnCheckedChangeListener event.
Try like this...
CheckBox ChkBx = ( CheckBox ) findViewById( R.id.checkbox);
ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
You can use following:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
Or u can save position as tag to checkbox and check on checkbox clicklistener
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// ur code...
**cb.setTag(position);**
row.setOnClickListener(this);
return row;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
**int position = v.getTag();** //cast & check for Tag not null too.
Toast toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
toast.show();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row = convertView;
if(row==null)
{ // Object reuse
inflater = getLayoutInflater();
row = inflater.inflate(R.layout.favorite_row, parent, false);
}
stationName1 = (TextView)row.findViewById(R.id.textFavoriteItemInRow);
stationName1.setText(stationNames[position]);
cb=(CheckBox)row.findViewById(R.id.cbCheck);
cb.setOnCheckedChangeListener(new CompoundButton.
OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked)
{
cb.setChecked(isChecked);
Toast toast = Toast.makeText(getApplicationContext(), "checked" + position, Toast.LENGTH_SHORT);
toast.show();
}
else
{
cb.setChecked(isChecked);
Toast toast = Toast.makeText(getApplicationContext(), "unChecked" + position, Toast.LENGTH_SHORT);
toast.show();
}
}
});
return row;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder holder;
// Reuse an existing view, if one is supplied, otherwise create a new one
// Check to see if this one is created yet ?
if (convertView == null){
// Get inflater
LayoutInflater inflater = (LayoutInflater)
parentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create a view for it
convertView = inflater.inflate(R.layout.test_reprot_lv_items, parent, false);
// Creates a holder class to contain all objects of a row
holder = new viewHolder();
holder.equipmentID = (TextView) convertView.findViewById(R.id.equipmentID);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set checkBox's Tag with the position of the row in the listview
holder.checkBox.setTag(position);
// Sets the tag associated with this view for later reuse.
convertView.setTag(holder);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
holder.checkBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int location = (Integer) c.getTag();
// Set selected state with the location of the row in the listview
itemsList.get(location).setSelectedState(c.isChecked());
}
});
}
else{
// In order to reuse the preallocated memory, get the holder from View's tag,
// which is allocated and saved in this view object. When a view requests
// to be rendered and it has not been instantiated, we new a holder and save
// it to View's 'Tag' for later reuse.
holder = (viewHolder) convertView.getTag();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set checkBox's Tag with the position of the row in the listview
holder.checkBox.setTag(position);
holder.checkBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int location = (Integer) c.getTag();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set selected state with the location of the row in the listview
// The method setSelectedState, which provided by your own class,
// is called to update the checkbox state.
itemsList.get(location).setSelectedState(c.isChecked());
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set checkbox state with calling the method getSelectedState which
// provied by your own class.
holder.checkBox.setChecked(itemsList.get(position).getSelectedState());
return convertView;
}
Related
Getview method of adapter.
#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.list_items, parent, false);
tvName = (TextView) rowView.findViewById(R.id.tvName);
tvPrice = (TextView) rowView.findViewById(R.id.tvPrice);
id = Integer.parseInt(values.get(position));
tvName.setText(database.getItemName(id));
spQuantity = (Spinner) rowView.findViewById(R.id.spQuantity);
spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3) {
// TODO Auto-generated method stub
String selectedQuantity = parent.getItemAtPosition(position)
.toString();
int selectedPrice = database.getPrice(id, selectedQuantity);
Log.d("selectedPrice",""+selectedPrice); //showing correct value
tvPrice.setText("Rs. " + selectedPrice); //not working
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
quantityList = database.getQuantityList(id);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
R.layout.spinner_item_black, quantityList);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spQuantity.setAdapter(dataAdapter);
buttonAddtoCart = (LinearLayout) rowView
.findViewById(R.id.buttonAddtoCart);
buttonAddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (database.checkDuplicateCart(id)) {
Toast.makeText(context, "Already added to cart",
Toast.LENGTH_SHORT).show();
} else {
database.addtoCart(id);
Toast.makeText(context, "Added to cart", Toast.LENGTH_SHORT)
.show();
}
}
});
return rowView;
}
Log shows the correct value fetched from the database. Everything else is working fine. But the TextView is not changing its value. Only the last row of listview's TextView is changing its value for first time. But when we wait for some time(about 30 secs), the text view changes. Why this takes so much time?
Some times Spinner in listview will not work as like we want, try to save your selected value in local variable and set the value in text view, try my below answer
let me know it is working or not
//This must be initialize only once
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Try to initialize TextView each and every time inside the getView. i have tried with Base adapter its working fine
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String Spinnerselecteditem;
View rowView = inflater.inflate(R.layout.list_items, parent, false);
TextView tvName = (TextView) rowView.findViewById(R.id.tvName);
TextView tvPrice = (TextView) rowView.findViewById(R.id.tvPrice);
id = Integer.parseInt(values.get(position));
tvName.setText(database.getItemName(id));
Spinner spQuantity = (Spinner) rowView.findViewById(R.id.spQuantity);
quantityList = database.getQuantityList(id);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
R.layout.spinner_item_black, quantityList);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spQuantity.setAdapter(dataAdapter);
spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long arg3) {
// TODO Auto-generated method stub
String selectedQuantity = parent.getItemAtPosition(position)
.toString();
int selectedPrice = database.getPrice(id, selectedQuantity);
Log.d("selectedPrice",""+selectedPrice); //showing correct value
Spinnerselecteditem = String.ValueOf(selectedPrice); //save it in a local variable
tvPrice.setText("Rs. " + Spinnerselecteditem);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
LinearLayout buttonAddtoCart = (LinearLayout) rowView
.findViewById(R.id.buttonAddtoCart);
buttonAddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (database.checkDuplicateCart(id)) {
Toast.makeText(context, "Already added to cart",
Toast.LENGTH_SHORT).show();
} else {
database.addtoCart(id);
Toast.makeText(context, "Added to cart", Toast.LENGTH_SHORT)
.show();
}
}
});
return rowView;
}
I have a custom listview with each row contaning a checkbox and text. now what i want that if any one checkbox of listview row is checked so others checkbox in other row if checked .it will be delected automatically.(i.e only one checkbox should be selected one at a time).how should i do that.
So far what i have done is as follows:
public class CustomAdapter extends BaseAdapter{
Context context;
List<String> items;
boolean array[];
public CustomAdapter(Context context, List<String> items) {
super();
this.context = context;
this.items = items;
array =new boolean[items.size()];
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertView;
final int pos=position;
if(v==null)
{
v=LayoutInflater.from(context).inflate(R.layout.list,null);
}
TextView txt1=(TextView) v.findViewById(R.id.textView1);
final CheckBox chkbox=(CheckBox) v.findViewById(R.id.checkBox1);
txt1.setText(items.get(position));
int selectedindexitem=0;
chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(chkbox.isChecked())
{
array[pos]=true;
}else{
array[pos]=false;
}
}
});
chkbox.setChecked(array[pos]);
return v;
}
}
In this code i can select multiple checkbox at a time but i need only one checkbox should be checked one at a time.
You need to keep track of selected item and code accordingly.
public class CustomAdapter extends BaseAdapter{
Integer selected_position = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Your Code
chkbox.setChecked(position==selected_position);
chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
selected_position = position;
}
else{
selected_position = -1;
}
notifyDataSetChanged();
}
});
return convertView;
}
}
Try to change all item boolean value false exclude selected item after notify adapter and also implement ViewHolder design pattern for ListView performance :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list,null);
holder.txt1 = (TextView) convertView.findViewById(R.id.textView1);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txt1.setText(items.get(position));
holder.chkbox.setChecked(array[position]);
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<array.length;i++){
if(i==position){
array[i]=true;
}else{
array[i]=false;
}
}
notifyDataSetChanged();
}
});
return convertView;
}
class ViewHolder{
TextView txt1;
CheckBox chkbox;
}
Maintain a variable:
int checked = -1; //say
Whenever you try to check a checkbox you check this variable, if it is -1 then check the checkbox and save the position of the list item in checked variable, when you try to check other checkbox again, if the variable ain't equal to -1 you first uncheck the checkbox at the position stored in checked variable, and then check the checkbox at current position and save the current position in checked variable
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertView;
final int pos=position;
if(v==null)
{
v=LayoutInflater.from(context).inflate(R.layout.list,null);
}
TextView txt1=(TextView) v.findViewById(R.id.textView1);
final CheckBox chkbox=(CheckBox) v.findViewById(R.id.checkBox1);
txt1.setText(items.get(position));
int selectedindexitem=0;
if(position==selected_position)
{
chkbox.setChecked(true);
}
else
{
chkbox.setChecked(false);
}
chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(chkbox.isChecked())
{
array[pos]=true;
selected_position = pos;
}else{
array[pos]=false;
}
}
});
chkbox.setChecked(array[pos]);
MainActivity.lv.setAdapter(new CustomAdapter(context,MainActivity.listitems));
return v;
}
Easy to maintain your selection. Get your selection from the model.
class PropertyModel{
String VAL= "SOME VALUE"
boolean selected = false;
public String getVAL() {return VAL;}
public void setVAL(String VAL) {this.VAL = VAL;}
public boolean isSelected() {return selected;}
public void setSelected(boolean selected) {this.selected = selected;}
}
Prepare your view like this:
public class CheckBoxAdptr extends BaseAdapter{
/*
..........
*/
public View getView(int position, View view, ViewGroup parent) {
PropertyModel items = list.get(position);
View row;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_checkbox, null);
}
else{row = view;}
TextView T1 = (TextView) row.findViewById(R.id.list_item_1);
CheckBox checkBox = (CheckBox) row.findViewById(R.id.list_item_check_box);
T1.setText(""+items.getVAL());
if(items.isSelected()){
checkBox.setChecked(true);
}
else {checkBox.setChecked(false);}
return row;
}
}
Now in your activity or fragment set the adapter and do something like this:
final ArrayList<PropertyModel> list = getList();
CheckBoxAdptr adpt = new CheckBoxAdptr(getActivity(), list);
listview.setAdapter(adpt);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
for(int i = 0; i<list.size(); i++){
if(i!=position){
list.get(i).setSelected(false);
}
else{
list.get(i).setSelected(true);
}
}
adpt.notifyDataSetChanged();
}
});
Notice that all your work is done by adpt.notifyDataSetChanged() . Hope this helps.
Working with getView (like most of the answers posted) was not working properly for me. It was not responsive enough. Sometimes it would uncheck the previous checkbox, sometimes not.
This worked perfectly for me:
First we need to store the position of all previously checked checkboxes:
Set<Integer> selectedPreviousPositions = new HashSet<>();
Then in the onItemClick listener we uncheck all checkboxes before checking the one we selected.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isChecked = ((CheckBox) view.findViewById(R.id.cbSelected)).isChecked();
if (!isChecked) {
final ListView listDevices = (ListView) findViewById(R.id.lvDevices);
for (Integer pos : selectedPreviousPositions ) {
View pView = listDevices.getChildAt(pos);
if (pView != null) { // unnecessary but we never know !
((CheckBox)pView.findViewById(R.id.checkboxID)).setChecked(false);
}
}
selectedUniquePositions.add(new Integer(position));
// Now we can check the selected checkbox
((CheckBox) view.findViewById(R.id.cbSelected)).setChecked(true);
} else {
((CheckBox) view.findViewById(R.id.cbSelected)).setChecked(false);
selectedPreviousPositions.remove(new Integer(position));
}
}
Inside the adapter, set OnClickListener() for checkBox. Whenever checkBox is clicked, store clicked checkBox position and call notifyDataSetChanged(). This will getView() method again for all views in your listview. Whenever, getView() called, you check the checkBox of previously stored postition and uncheck remaining checkboxes.
public class CustomAdapter extends ArrayAdapter<YourModelObject>
{
private int selectedCheckBoxPosition = -1;
public int getSelectedCheckBoxPosition()
{
return selectedCheckBoxPosition;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent)
{
final ViewHolder viewHolder;
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = layoutInflater.inflate(R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) convertView;
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
if (position == selectedCheckBoxPosition)
{
viewHolder.checkBox.setChecked(true);
Log.d(TAG, "checkbox CHECKED at pos: " + position);
}
else
{
viewHolder.checkBox.setChecked(false);
Log.d(TAG, "checkbox UNCHECKED at pos: " + position);
}
//viewHolder.checkBox.setText("sample text");
viewHolder.checkBox.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
selectedCheckBoxPosition = position;
Log.d(TAG, "onClick() - set selectedCheckBoxPosition = " + position);
notifyDataSetChanged();
}
});
return convertView;
}
private class ViewHolder
{
CheckBox checkBox;
}
}
Here is my adapter class:-
public class CustomAdapter extends BaseAdapter {
Context c;
CustomAdapter(Context c)
{
this.c=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int pos=position;
LayoutInflater inflater=LayoutInflater.from(c);
View v=inflater.inflate(R.layout.layout_list_item, parent, false);
ImageButton image_button=v.findViewById(R.id.imagebutton);
image_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(c, "Image Button clicked:" + pos, Toast.LENGTH_SHORT).show();
}
});
return v;
}
}
How do I make all imagebuttons clickable? I tried searching for answers and as per an answer given here: how to make an imageview clickable in an listview I tried but only my first row button is clickable. Please help.
In your custom adapter constructor
LayoutInflater mInflater;
CustomAdapter(Context c)
{
mInflater = LayoutInflater.from(c);
// initialize inflater in the constructor.
// need not initialize everytime getView is called.
}
Use a View Holder
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
static class ViewHolder
{
ImageButton ib;
}
#Override
public View getView(int position, View item, ViewGroup parent) {
ViewHolder holder;
if(item == null){
item = mInflater.inflate(R.layout.elementos_lista_temas, null);
holder = new ViewHolder();
holder.ib = (ImageButton) item.findViewById(R.id.imagebutton);
item.setTag(holder);
}
else{
holder = (ViewHolder)item.getTag();
}
return item;
}
Then in your activity class
ListView lv = (ListView) findViewById(R.id.listview);
CustomAdapter cus = new CustomAdapter(this);
lv.setAdapter(cus);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemId)
{
Toast.makeText(ActivityName.this, "Image Button clicked:" + itemPosition, Toast.LENGTH_SHORT).show();
}
});
As told by "the World of Listview-2010" see below link show how to use viewholder class with custom listview in android http://impressive-artworx.de/2011/list-all-installed-apps/ Hope this helps you.
I've a ListView where every element in the list contains a TextView and two different Buttons. Something like this:
ListView
--------------------
[ImageView][Text][CheckBox][Button]
--------------------
[ImageView][Text][CheckBox][Button]
--------------------
... (and so on) ...
With this code I can create an OnItemClickListener for the whole item:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> list, View view, int position, long id) {
Log.i(TAG, "onListItemClick: " + position);
}
}
});
However, I don't want the whole item to be clickable, but only the checkbox and the button of each list element.
So my question is, how do I implement a onClickListener for these two buttons with the following parameters:
int id (some id associated with each item in list)
int position (which is the element in the list on which the button click happened)
you need to make baseAdpter to achieve this
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}
i solved the same problem in this way:
in the layout.xml of the ListViewItem give the elements a tag, where you want to add the OnClickListener:
android:id="#+id/CheckBox"
android:tag="CheckBox" />
....
android:id="#+id/Button"
android:tag="Button" />
In the code, where your ListView is inflated add the OnClickListener with the following code:
listView.findViewWithTag("CheckBox").setOnClickListener(createCheckBoxOnClickListener(act));
listView.findViewWithTag("Button").setOnClickListener(createButtonOnClickListener(act));
You must do this in the getView method in your adapter..
easy, just implement the OnClickListener for these two buttons, and get the position that you get from getView(), make sure you set the position to final in order to get it in OnClickListener
you can add listeners in your getView() method of Adapter.
dont add onItemClickListener for the listview rather add onClick for your required button and for checkbox do it like this CheckBox cbox = new CheckBox(this);// find your checkbox from the view here.
cbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
// do what ever you want.
}
}
});
check below code it may help you.
private class ListViewAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ListViewAdapter(Context con) {
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(con);
}
public int getCount() {
// TODO Auto-generated method stub
return main_genral_class.review_name.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListContent holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.review_row, null);
holder = new ListContent();
holder.img = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.name = (TextView) convertView
.findViewById(R.id.textView1);
holder.check_date = (TextView) convertView
.findViewById(R.id.textView2);
holder.img.setOnClickListener(mOnTitleClickListener);
holder.name.setOnClickListener(mOnTitleClickListener1);
holder.check_date.setOnClickListener(mOnTitleClickListener2);
convertView.setTag(holder);
} else {
holder = (ListContent) convertView.getTag();
}
holder.text2.setText(main_genral_class.review_shout.get(position));
return convertView;
}
}
private OnClickListener mOnTitleClickListener = new OnClickListener() {
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v
.getParent());
Toast.makeText(review_activity.this, "click on Image View",
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mOnTitleClickListener1 = new OnClickListener() {
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v
.getParent());
Toast.makeText(review_activity.this, "click on Text View",
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mOnTitleClickListener2 = new OnClickListener() {
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v
.getParent());
Toast.makeText(review_activity.this, "click on Date Text View",
Toast.LENGTH_SHORT).show();
}
};
Below I have written my code actually when I was scrolling my listview the checkbox takes its original position, any help by code will be appreciated.
cp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
cp.setChecked(true);
cx.setChecked(false);
ck.setChecked(false);
int a=1;
String c=getListView().getItemAtPosition(position).toString();
updatetable(c, "FULL");
//Toast.makeText(getApplicationContext(), c+"full", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "year", Toast.LENGTH_LONG).show();
}
});
cx.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
cx.setChecked(true);
cp.setChecked(false);
ck.setChecked(false);
int a=1;
String c=getListView().getItemAtPosition(position).toString();
updatetable(c, "CRITICAL");
//Toast.makeText(getApplicationContext(), c+"ok", Toast.LENGTH_LONG).show();
}
});
ck.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ck.setOnCheckedChangeListener(null);
// TODO Auto-generated method stub
ck.setChecked(true);
cp.setChecked(false);
cx.setChecked(false);
int a=1;
String c=getListView().getItemAtPosition(position).toString();
updatetable(c, "FINISH");
//Toast.makeText(getApplicationContext(), c+"fineshed", Toast.LENGTH_LONG).show();
}
});
Your question is not clear, but I think I got the problem.
I think this is not a matter of CheckBox. I think you're doing something wrong with your adapter.
public class MyAdapter extends BaseAdapter {
private List<Something> mList;
private Context mContext;
public MyAdapter(Context context, List<Something> list) {
mContext = context;
mList = list;
}
#Override
public int getCount() {
return mList.getSize();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_layout, null);
}
CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
/* Here you should set your checkbox state */
}
}
I think your problem is convertView.
When you scroll down your ListView the popped up items are not destroyed, but recycled. The recycled item is given you back as convertView. convertView is not cleaned, hence if the CheckBox in the popped out item was checked, the CheckBox in convertView is checked.
You have to maintain a List<Boolean> states where you save the state of the CheckBox of all your items. Then:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_layout, null);
}
CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
checkBox.setChecked(states.get(position));
}
I haven't your code, so the example above is as general as possible. If you let us see the code we can help you.