CheckBox showing unusual behaviour in Android - android

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.

Related

how to check the check box in ListView and change the text in same row in listView?

I have list view with check box and text view. When i checked check box, change the text in same row. This way i will check all the check boxes in list view and change the text in every row. Can any one explain with sample code?
public class DialogAdapter extends BaseAdapter{
//private LayoutInflater inflater = null;
ArrayList<String> timeList = new ArrayList<String>();
Context context;
public DialogAdapter(Context context, ArrayList<String> timeList) {
// TODO Auto-generated constructor stub
this.context = context;
this.timeList = timeList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return timings.size();
return timeList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return timeList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//String timing = "10-30,14-08,16-30,19-00";
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.dialog_row_list,null);
//timeListView.setVisibility(convertView.VISIBLE);
TextView txt_time=(TextView) convertView.findViewById(R.id.text_times);
txt_time.setText(timeList.get(position).toString());
EditText comments=(EditText)convertView.findViewById(R.id.editText_comment);
final TextView txt_Action=(TextView) convertView.findViewById(R.id.textView_act);
CheckBox cBox= (CheckBox) convertView.findViewById(R.id.checkBox_action);
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#SuppressLint("ResourceAsColor")
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int getPosition = (Integer) buttonView.getTag();
timeList.get(getPosition).setSelected(buttonView.isChecked());
Toast.makeText(context, "position"+getPosition, 0).show();
if(isChecked){
txt_Action.setText("finished");
txt_Action.setTextColor(R.color.Green);
}
else{
txt_Action.setText("UnChecked");
txt_Action.setTextColor(R.color.Red);
}
}
});
return convertView;
}
}
this is my code please check n give solution how to change listview text when check checkbox in listview???
in the getView method of your ListView adapter:
if(yourCheckBox.isChecked)
yourTextView.setText("text if checkBox is checked.");
else
yourTextView.setText("text if checkBox is not checked.");
There is view before checkboxes and texviews that is listview ,if u want to access textviews from listview please make sure you are accessing from listview one item layout
Like
TextView txtvw=findViewByID(ur_layout_of_list_item).findViewByID(ur_textview);
after that changes will be done.
First I will suggest you to use ViewHolder pattern for listview adapter so that you don't need to do findViewById() everytime you scroll your list this will prevent your listview from performance slow down and also I would prefer to use setOnClickListener() over CheckedChangeListener().
Below is the sample code you can try
public class CustomAdapter extends BaseAdapter {
private Context context;
public static ArrayList<Item> modelArrayList;
public CustomAdapter(Context context, ArrayList<Item> modelArrayList){
this.context = context;
this.modelArrayList = modelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return modelArrayList.size();
}
#Override
public Object getItem(int position) {
return modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Item currentItem = (Item) getItem(position);
if(currentItem.isChecked())
viewHolder.tvName.setText("Checked);
else
viewHolder.tvName.setText("Unchecked);
viewHolder.checkBox.setChecked(currentItem.isChecked());
viewHolder.checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final boolean checked = currentItem.isChecked();
if(checked){
viewHolder.checkBox.setChecked(!checked);
viewHolder.tvName.setText("Unchecked");
currentItem.setChecked(!checked);
}else{
viewHolder.checkBox.setChecked(checked);
viewHolder.tvName.setText("Checked");
currentItem.setChecked(checked);
}
}
});
return convertView;
}
private class ViewHolder {
protected CheckBox checkBox;
private TextView tvName;
public ViewHolder(View view) {
checkBox = (CheckBox)view.findViewById(R.id.checkbox);
tvName = (TextView) view.findViewById(R.id.textView);
}
}
}

custom listview with only one checkbox is selected one at a time

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;
}
}

click listener + checkbox - on android

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;
}

Android: ListView elements with multiple clickable elements

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();
}
};

Data repeating in android list view

I have a list view whose adapter is in a different class in a different package. Now I have to get the data from database then I set Adapter for my list view using this data. So I have created an ArryList and pass this in the constructor of Adapter while seeting it for the list view. But the problem is that the data is repeating. eg.- there are 12 distinct Strings in the arraylist but what I get is -first five elements in order and after that the same five are being repeated. The count of data is always right but the position will always be 0,1,2,3,4 . I can not understand what the problem is . here is the code -
public class CheckboxAdapter extends BaseAdapter{
LayoutInflater inflater ;
ArrayList<String> mData = new ArrayList<String>();
//constructor for lesion adapter
public CheckboxAdapter (Context context, ArrayList<String> data){
inflater = LayoutInflater.from(context);
mData = data;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
Log.v("pos", ""+position);
convertView = inflater.inflate(R.layout.e_lesion_liststyle, null);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.disease_lesion_checkbox);
cb.setText(mData.get(position));
cb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
cb.setButtonDrawable(R.drawable.check_box_1);
}
});
}//end of if condition
return convertView;
}
try this.. just write all code out of the condition expect inflate code..
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
Log.v("pos", ""+position);
convertView = inflater.inflate(R.layout.e_lesion_liststyle, null);
} //end of if condition
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.disease_lesion_checkbox);
cb.setText(mData.get(position));
cb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
cb.setButtonDrawable(R.drawable.check_box_1);
}
});
return convertView;
}

Categories

Resources