I have stored some value in arraylist if checkbox is clicked but i am having a difficult time to get it from listView class. How can i get it. Also if I keep
clickListener in view that contains checkbox and textView, the checkbox click is not working but if i click in textview it works. How to fix it. Below is my code.
Thanks in advance
singlerow_compare.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/singleRow" android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewCompare" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewCompare"/>
</RelativeLayout>
listview xml:
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listViewCompare" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Compare"
android:id="#+id/compare"
android:layout_alignParentBottom="true"/>
ListView.java
listView = (HorizontalListView) findViewById(R.id.listViewCompare);
compareBtn = (Button) findViewById(R.id.compare);
listView.setAdapter(new CustomAdapter(this, nameList, imageList));
compareBtn.setOnClickListener(new View.OnClickListener()
{ #Override
public void onClick(View view) {
//I need to have addCheckBoxValue arraylist from adapter here
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
ArrayList result;
Context context;
Drawable [] imageId;
protected ArrayList<String> addCheckBoxValue;
private static LayoutInflater inflater=null;
public CustomAdapter(CompareListView mainActivity, ArrayList nameList, Drawable[] imageList) {
result=nameList;
context=mainActivity;
imageId=imageList;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public class Holder
{
TextView tv;
ImageView img;
CheckBox checkBox;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
addCheckBoxValue = new ArrayList();
final Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.singlerow_compare, null);
holder.tv=(TextView) rowView.findViewById(R.id.textViewCompare);
holder.checkBox = (CheckBox) rowView.findViewById(R.id.imageViewCompare);
holder.tv.setText(result.get(i).toString());
holder.checkBox.setButtonDrawable(imageId[i]);
final String selectedCbValue = holder.tv.getText().toString();
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean checked = ((CheckBox) view).isChecked();
if(checked){
if (!addCheckBoxValue.contains(selectedCbValue))
addCheckBoxValue.add(selectedCbValue);
}else{
if (addCheckBoxValue.contains(selectedCbValue))
addCheckBoxValue.remove(selectedCbValue);
}
}
});
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if i click on textView, it works but when i click on checkbox here, it doesnt work why?? So i have clicklistener in checkbox abov
}
});
return rowView;
}
Create Following method in your CustomAdapter class:
public ArrayList<String> getCheckBoxValue(){
return addCheckBoxValue;
}
And in your ListActivity. Change your activity code like this:
private CustomAdapter listAdapter; // declare this before on create
Now where you are setting adapter in your on create write this code:
listAdapter = new CustomAdapter(this, nameList, imageList)
// set Adapter like this:
listView.setAdapter(listAdapter);
your button on click code should be like this:
compareBtn.setOnClickListener(new View.OnClickListener()
{ #Override
public void onClick(View view) {
//I need to have addCheckBoxValue arraylist from adapter here
listAdapter.getCheckBoxValue(); // do whatever you want to do here
}
}
Happy Coding!!!
I suggest you make boolean array for checkbox and maintain it like this way,this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelPooja> listData;
public CustomAdapter(Context mainActivity, List<ModelPooja> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelPooja item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
Related
I'm trying to implement a selection activity for a given list of items. Each item is checkable, so I have an item with a TextView and a CheckBox. I implemented a ListView for displaying all the options and a Spinner for showing only the "Top Ten" choices, as a subset of the same list. For now I'm showing all the items in both ListView and Spinner.
I want for the items in the ListView to update when the user selects an item in the Spinner (Note: The reverse path works fine, as the Spinner grabs the updated ArrayList each time it dropsdown).
I tried to implement setOnItemSelectedListener for my Spinner, and to call notifyOnDataSetChanged() for my ListViewAdapter inside the Listener. But the Listener is only called on collapse and I get a weird (maybe unrelated) warning message.
The onItemSelectedListener for the Spinner only runs when the Spinner gets collapsed. But notifyOnDataSetChanged() seems to ignore the checked status of the items as a change. How can I make the first option run everytime I check an item and have the change get properly received by the ListAdapter?
Here's the Activity.java code:
public class TriageReasonActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_triage_reason);
final String[] select_qualification = {
"Select Qualification", "10th / Below", "12th", "Diploma", "UG",
"PG", "Phd"};
Spinner spinner = (Spinner) findViewById(R.id.top_reasons_spinner);
ListView symptoms_list = (ListView) findViewById(R.id.view_list_symptoms);
ArrayList<Symptoms> listVOs = new ArrayList<>();
for (int i = 0; i < select_qualification.length; i++) {
Symptoms reason = new Symptoms();
reason.setTitle(select_qualification[i]);
reason.setSelected(false);
listVOs.add(reason);
}
SymptomsListAdapter mListAdapter = new SymptomsListAdapter(this, 0,
listVOs);
SymptomsSpinnerAdapter mSpinnerAdapter = new SymptomsSpinnerAdapter(this, 0,
listVOs);
symptoms_list.setAdapter(mListAdapter);
spinner.setAdapter(mSpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.i("Item selected", "but not cahnged");
symptoms_list.invalidateViews();
mListAdapter.notifyDataSetInvalidated();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
Log.i("Not item selected", "but actually it did");
}
});
}
The SpinnerCustom Adapter code:
public class SymptomsSpinnerAdapter extends ArrayAdapter<Symptoms>{
private Context mContext;
private ArrayList<Symptoms> listState;
private SymptomsSpinnerAdapter myAdapter;
private boolean isFromView = false;
/*#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
//mNotifyOnChange = true;
}*/
public SymptomsSpinnerAdapter(Context context, int resource, List<Symptoms> objects) {
super(context, resource, objects);
this.mContext = context;
this.listState = (ArrayList<Symptoms>) objects;
this.myAdapter = this;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(mContext);
convertView = layoutInflator.inflate(R.layout.item_reasons, null);
holder = new ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mTextView.setText(listState.get(position).getTitle());
// To check weather checked event fire from getview() or user input
isFromView = true;
holder.mCheckBox.setChecked(listState.get(position).isSelected());
isFromView = false;
if ((position == 0)) {
holder.mCheckBox.setVisibility(View.INVISIBLE);
} else {
holder.mCheckBox.setVisibility(View.VISIBLE);
}
holder.mCheckBox.setTag(position);
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
if (!isFromView) {
listState.get(position).setSelected(isChecked);
}
}
});
return convertView;
}
#Override
public int getCount() {
return listState.size();
}
#Override
public Symptoms getItem(int position) {
if( position < 1 ) {
return null;
}
else {
return listState.get(position-1);
}
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
private TextView mTextView;
private CheckBox mCheckBox;
}
}
Here's the (almost identical) ListAdapter:
public class SymptomsListAdapter extends BaseAdapter implements ListAdapter {
private Context mContext;
private ArrayList<Symptoms> listState;
private boolean isFromView = false;
public SymptomsListAdapter(Context context, int resource, List<Symptoms> objects) {
this.mContext = context;
this.listState = (ArrayList<Symptoms>) objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(mContext);
convertView = layoutInflator.inflate(R.layout.item_reasons, null);
holder = new SymptomsListAdapter.ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (SymptomsListAdapter.ViewHolder) convertView.getTag();
}
holder.mTextView.setText(listState.get(position).getTitle());
// To check weather checked event fire from getview() or user input
isFromView = true;
holder.mCheckBox.setChecked(listState.get(position).isSelected());
isFromView = false;
if ((position == 0)) {
holder.mCheckBox.setVisibility(View.INVISIBLE);
} else {
holder.mCheckBox.setVisibility(View.VISIBLE);
}
holder.mCheckBox.setTag(position);
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
if (!isFromView) {
listState.get(position).setSelected(isChecked);
}
}
});
return convertView;
}
#Override
public int getCount() {
return listState.size();
}
#Override
public Symptoms getItem(int position) {
if( position < 1 ) {
return null;
}
else {
return listState.get(position-1);
}
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
public TextView mTextView;
public CheckBox mCheckBox;
}
}
And here's the warning I'm getting:
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
EDIT: Adding the layouts and the model class in case they may cause an issue:
Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="demo.hb.activity.visit.TriageReasonActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textFontWeight="6dp"
android:textSize="30sp"
android:layout_margin="20dp"
android:textAlignment="center"
android:textColor="#000000"
android:text="What is the reason for your visit?" />
<Spinner
android:id="#+id/top_reasons_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_list_symptoms"
android:layout_above="#+id/next_btn"
android:layout_alignParentTop="true"/>
</RelativeLayout>
</LinearLayout>
</FrameLayout>
Item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:text="text"
android:textAlignment="gravity" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Model Class:
public class Symptoms {
private String title;
private boolean selected;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
The reason that nothing is changing is because you haven't implemented the method to handle the data set changes. You need to handle how the data is reloaded in your adapter:
public class SymptomsListAdapter extends BaseAdapter implements ListAdapter {
...
public void refreshData(ArrayList<Symptoms> objects){
this.listState = (ArrayList<Symptoms>) objects;
notifyDataSetChanged();
}
...
}
This link does a great job of explaining how the notifyDataSetInvalidated() works (or in your case, why it's not working).
I want to put button below ListView and have everything inside ScrollView(not only ListView should be scrollable but button too so if ListView has a lot of elements button is invisible and user has to scroll down to click it).
My xml is:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.plan.aplikacjamobilna.fragments.tabs.Allergies">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center_horizontal">
<ListView
android:id="#+id/allergies_listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="3dp"
android:divider="#cccccc">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>
</ScrollView>
it looks like:
I'm not sure why it doesn't work, there is "match_parent" as layout_hight.
What shuld I change in my code?
my Adapter:
public class AllergiesAdapter extends ArrayAdapter{
List list = new ArrayList();
char[] keys;
public AllergiesAdapter(Context context, int resource) {
super(context, resource);
}
public static class DataHandler{
ImageView allergieIcon;
ImageView showDetailsIcon;
TextView allergieName;
FrameLayout detailsLayout;
RelativeLayout infoLayout;
CheckBox checkBox;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final DataHandler dataHandler;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.allergie_item,parent,false);
dataHandler = new DataHandler();
dataHandler.allergieIcon = (ImageView) view.findViewById(R.id.allerie_icon);
dataHandler.showDetailsIcon = (ImageView) view.findViewById(R.id.allergie_show_info);
dataHandler.allergieName =(TextView) view.findViewById(R.id.allerie_name);
dataHandler.detailsLayout=(FrameLayout)view.findViewById(R.id.allergie_frameLayout);
dataHandler.infoLayout=(RelativeLayout)view.findViewById(R.id.info_layout);
dataHandler.checkBox=(CheckBox)view.findViewById(R.id.allergie_checkbox);
view.setTag(dataHandler);
}
else{
dataHandler=(DataHandler) view.getTag();
}
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final AllergiesDataProvider allergiesDataProvider;
allergiesDataProvider = (AllergiesDataProvider) this.getItem(position);
dataHandler.allergieIcon.setImageResource(allergiesDataProvider.getAllergieIcon());
dataHandler.showDetailsIcon.setImageResource(allergiesDataProvider.getShowDetailsIcon());
dataHandler.allergieName.setText(allergiesDataProvider.getAllergieName());
dataHandler.showDetailsIcon.setImageResource(allergiesDataProvider.getShowDetails());
allergiesData = getContext().getSharedPreferences("allergiesData", Context.MODE_PRIVATE);
allergiesEditor = allergiesData.edit();
String myKey = allergiesData.getString(ALLERIES_KEY,"00000000");
keys = myKey.toCharArray();
if(keys[position]=='0')
dataHandler.checkBox.setChecked(false);
else
dataHandler.checkBox.setChecked(true);
dataHandler.infoLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getContext(),"no elo",Toast.LENGTH_LONG).show();
if (!allergiesDataProvider.isDetailsShows()) {
allergiesDataProvider.setIsDetailsShows(true);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dataHandler.detailsLayout.removeAllViews();
dataHandler.detailsLayout.addView(inflater.inflate(allergiesDataProvider.getDetailsLayout(), dataHandler.detailsLayout, false));
dataHandler.showDetailsIcon.setImageResource(allergiesDataProvider.getHindDetails());
} else {
allergiesDataProvider.setIsDetailsShows(false);
dataHandler.detailsLayout.removeAllViews();
dataHandler.showDetailsIcon.setImageResource(allergiesDataProvider.getShowDetails());
}
}
});
dataHandler.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
keys[position] = '1';
else
keys[position] = '0';
String myString = String.valueOf(keys);
allergiesEditor.putString(ALLERIES_KEY,myString).apply();
//Toast.makeText(getContext(),allergiesData.getString(ALLERIES_KEY,"Sd"),Toast.LENGTH_LONG).show();
}
});
return view;
}
}
You can use this function to set the height of list view based on your children.
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
Example:
setListViewHeightBasedOnChildren(yourlistview);
A ListView is scrollable on it's own and should not be wrapped in a ScrollView. For your use, what you should do is to simply have the ListView as it is and have the button as the last view in the ListView. You will have to modify the getview() method in your adapter to achieve this. Based on the index, you will return a view that displays a Button.
I suggest you to use RecyclerView with footer as a button like this way,and also try HFRecyclerView
public class HeaderFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
ArrayList<Generic> generics;
Context context;
public HeaderFooterAdapter(Context context, ArrayList<Generic> generics) {
this.context = context;
this.generics = generics;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if(viewType == TYPE_HEADER) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.header_item, parent, false);
return new HeaderViewHolder (v);
} else if(viewType == TYPE_FOOTER) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.footer_item, parent, false);
return new FooterViewHolder (v);
} else if(viewType == TYPE_ITEM) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.list_item, parent, false);
return new GenericViewHolder (v);
}
return null;
}
private Generic getItem (int position) {
return generics.get (position);
}
#Override
public void onBindViewHolder (RecyclerView.ViewHolder holder, int position) {
if(holder instanceof HeaderViewHolder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.txtTitleHeader.setText ("Header");
headerHolder.txtTitleHeader.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View view) {
Toast.makeText (context, "Clicked Header", Toast.LENGTH_SHORT).show ();
}
});
} else if(holder instanceof FooterViewHolder) {
FooterViewHolder footerHolder = (FooterViewHolder) holder;
footerHolder.txtTitleFooter.setText ("Footer");
footerHolder.txtTitleFooter.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View view) {
Toast.makeText (context, "Clicked Footer", Toast.LENGTH_SHORT).show ();
}
});
} else if(holder instanceof GenericViewHolder) {
Generic currentItem = getItem (position - 1);
GenericViewHolder genericViewHolder = (GenericViewHolder) holder;
genericViewHolder.txtName.setText (currentItem.getName ());
}
}
// need to override this method
#Override
public int getItemViewType (int position) {
if(isPositionHeader (position)) {
return TYPE_HEADER;
} else if(isPositionFooter (position)) {
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
private boolean isPositionHeader (int position) {
return position == 0;
}
private boolean isPositionFooter (int position) {
return position == generics.size () + 1;
}
#Override
public int getItemCount () {
return generics.size () + 2;
}
class FooterViewHolder extends RecyclerView.ViewHolder {
TextView txtTitleFooter;
public FooterViewHolder (View itemView) {
super (itemView);
this.txtTitleFooter = (TextView) itemView.findViewById (R.id.txtFooter);
}
}
class HeaderViewHolder extends RecyclerView.ViewHolder {
TextView txtTitleHeader;
public HeaderViewHolder (View itemView) {
super (itemView);
this.txtTitleHeader = (TextView) itemView.findViewById (R.id.txtHeader);
}
}
class GenericViewHolder extends RecyclerView.ViewHolder {
TextView txtName;
public GenericViewHolder (View itemView) {
super (itemView);
this.txtName = (TextView) itemView.findViewById (R.id.txtName);
}
}
}
I want to mark radio button true in listview onItemClick so what I am doing is
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
LinearLayout item_view = (LinearLayout) view;
final RadioButton itemcheck = (RadioButton) item_view
.findViewById(R.id.listview_radiobutton);
if (itemcheck.isChecked()) {
itemcheck.setChecked(true);
} else {
itemcheck.setChecked(false);
}
itemcheck.setChecked(true);
}
My listview
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginLeft="#dimen/view_margin_15"
android:layout_marginRight="#dimen/view_margin_15"
android:layout_marginTop="#dimen/view_margin_20"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:divider="#drawable/list_divider"
android:dividerHeight="#dimen/padding_2"
android:fastScrollEnabled="true"
android:footerDividersEnabled="true"
android:listSelector="#null"
android:scrollbars="none"
android:textFilterEnabled="true"
android:textStyle="normal" />
Edit:--
My Adapter code :--
public class Adapter extends ArrayAdapter<Details> {
private Context mContext;
private List<Details> transList;
private LayoutInflater infalInflater;
private OnCheckedRadioButon onCheckedRadioButon;
private Typeface mTypeface, mEditTypeface, mPasswdTypeface;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private PromoViewHolder viewHolder;
public Adapter(Context context, List<Details> mtransList, OnCheckedRadioButon onCheckedRadioButon) {
super(context, R.layout.dialog_listview, mtransList);
this.mContext = context;
this.transList = mtransList;
this.onCheckedRadioButon = onCheckedRadioButon;
this.infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try {
viewHolder = null;
row = infalInflater.inflate(R.layout.dialog_listview_code, parent, false);
viewHolder = new ViewHolder();
viewHolder.radiobutton = (RadioButton) row.findViewById(R.id.radiobutton);
viewHolder.listview_name = (TextView) row.findViewById(R.id.listview_name);
setValueText(viewHolder, position);
viewHolder.radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
onCheckedRadioButon.onCheckedButton(transList.get(position));
}
}
});
viewHolder.radiobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position != mSelectedPosition && mSelectedRB != null) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton) v;
}
});
if (mSelectedPosition != position) {
viewHolder.radiobutton.setChecked(false);
} else {
viewHolder.radiobutton.setChecked(true);
if (mSelectedRB != null && viewHolder.radiobutton != mSelectedRB) {
mSelectedRB = viewHolder.radiobutton;
}
}
row.setTag(viewHolder);
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
private void setValueText(ViewHolder viewHolder, final int position) {
viewHolder.listview_name.setText(transList.get(position).getName());
}
public interface OnCheckedRadioButon {
void onCheckedButton(Details pr);
}
class ViewHolder {
RadioButton radiobutton;
TextView listview_name;
}
}
It is working but if I click on another position of the listview then the previous radiobutton position is not unchecked.I want to uncheck all the previous ones and mark only one at a time.
Any help will be appreciated.
Use POJO classes (Setter or Getter) to manage this type of condition. Use boolean variable in that class and change its values according to the position true or false.
POJO Class Like :
public class CheckListSource {
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
In your adapter :
private ArrayList<CheckListSource > itemsData;
public ChildListAdapter(Activity activity, ArrayList<ChildListResponse> baseResponse) {
this.itemsData = baseResponse;
this.activity = activity;
}
In BindViewHolder Like :
viewHolder.checkParentView.setTag(itemsData.get(position));
viewHolder.checkParentView.setOnClickListener(checkedListener);
private View.OnClickListener checkedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckListSource childListResponse = (CheckListSource ) v.getTag();
if (childListResponse.isSelected())
childListResponse.setSelected(false);
else
childListResponse.setSelected(true);
notifyDataSetChanged();
}
};
Use a boolean array in your Activity. Each boolean value corresponds to a RadioButton.
If a RadioButton is checked, set its boolean value to true, and set all other boolean values in the array to false.
In the getView() of your Adapter, call your_radio_button.setChecked(your_boolean_array[position]).
Once the boolean array is modified, call your_adapter.notifyDataSetChanged().
Checkout this it works for me..
public class ProgramAdapter extends ArrayAdapter<KeyInformation> {
private final String TAG = "ProgramAdapter";
private List<KeyInformation> mList;
private Context mContext;
private LayoutInflater mInflater;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private String mUserApllication = "";
public ProgramAdapter(Context context, List<KeyInformation> objects) {
super(context, R.layout.program_item, objects);
mContext = context;
mList = objects;
mInflater = ( LayoutInflater ) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mUserApllication = Settings.System.getString(mContext.getContentResolver(),
Settings.System.PROGRAMMABLE_KEY_ACTION);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.program_item, parent, false);
holder.mImageView = (ImageView) convertView.findViewById(R.id.icon);
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mSeparator = (TextView) convertView.findViewById(R.id.title_separator);
holder.mRadioButton = (RadioButton) convertView.findViewById(R.id.radioBtn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mRadioButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false);
}
mUserApllication ="";
mSelectedPosition = position;
mSelectedRB = (RadioButton) view;
}
});
String userApp = mList.get(position).packageName;
if(mUserApllication.equals(userApp)) {
mSelectedPosition = position;
}
if (mSelectedPosition != position) {
holder.mRadioButton.setChecked(false);
} else {
holder.mRadioButton.setChecked(true);
mSelectedRB = holder.mRadioButton;
}
holder.mImageView.setImageDrawable(mList.get(position).icon);
holder.mTextView.setText(mList.get(position).lable);
if (position == 5) {
holder.mSeparator.setVisibility(View.VISIBLE);
} else {
holder.mSeparator.setVisibility(View.GONE);
}
return convertView;
}
public int getmSelectedPosition () {
return mSelectedPosition;
}
private static class ViewHolder {
ImageView mImageView;
TextView mTextView;
TextView mSeparator;
RadioButton mRadioButton;
}
}
Please go through below, it will work.
class Details{
public boolean isSelect=false;
}
public class Adapter extends ArrayAdapter<Details> {
private Context mContext;
private List<Details> transList;
private LayoutInflater infalInflater;
private OnCheckedRadioButon onCheckedRadioButon;
private Typeface mTypeface, mEditTypeface, mPasswdTypeface;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private PromoViewHolder viewHolder;
public Adapter(Context context, List<Details> mtransList, OnCheckedRadioButon onCheckedRadioButon) {
super(context, R.layout.dialog_listview, mtransList);
this.mContext = context;
this.transList = mtransList;
this.onCheckedRadioButon = onCheckedRadioButon;
this.infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateList(){
viewHolder.radiobutton.setChecked(false);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try {
viewHolder = null;
row = infalInflater.inflate(R.layout.dialog_listview_code, parent, false);
viewHolder = new ViewHolder();
viewHolder.radiobutton = (RadioButton) row.findViewById(R.id.radiobutton);
viewHolder.listview_name = (TextView) row.findViewById(R.id.listview_name);
setValueText(viewHolder, position);
viewHolder.radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
onCheckedRadioButon.onCheckedButton(transList.get(position));
}
}
});
viewHolder.radiobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Details detail=transList.get(position);
for(int i=0;i<transList.size;i++){
Detail b=transList.get(i);
b.isSelect=false;
}
detail.isSelect=true;
adapter.notifydatasetchange();
}
});
Details detail=transList.get(position);
if (detail.isSelect) {
viewHolder.radiobutton.setChecked(true);
} else {
viewHolder.radiobutton.setChecked(false);
}
row.setTag(viewHolder);
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
private void setValueText(ViewHolder viewHolder, final int position) {
viewHolder.listview_name.setText(transList.get(position).getName());
}
public interface OnCheckedRadioButon {
void onCheckedButton(PromoDetails promoDetails);
}
class ViewHolder {
RadioButton radiobutton;
TextView listview_name;
}
}
I have a row which is represented by an image, some text and a CheckBoxes. Whenever I'm trying to use the OnItemClickListener for the rows, the event won't fire up when clicking the CheckBoxes.
I also tried checkbox.onCheckedChangedListener but it gives me Null Pointer at findViewByID. I checked, the ID I am looking for is alright, no typos in there.
I'd like to make usage of this OnItemClickListener so later on I can play with the checkboxes. Any ideas?
Code:
ADAPTER:
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
#Override
public int getCount() {
return mFilters.size();
}
#Override
public Object getItem(int position) {
return mFilters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
return convertView;
}
}
Class where using the Adapter:
public class CheckinFilters extends Fragment {
private ListView mListView;
private FilterAdapter filterAdapter;
private ArrayList<String> l = new ArrayList<String>();
private ArrayList<Integer> drawables = new ArrayList<Integer>();
private Typeface Bebas;
private ArrayList<Integer> checkboxes = new ArrayList<Integer>();
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public CheckinFilters() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_checkin_filters, container, false);
l.add("Chill");
l.add("Eat");
l.add("Explore");
l.add("Move");
l.add("Party");
l.add("Whatever");
drawables.add(R.drawable.category_chill);
drawables.add(R.drawable.category_eat);
drawables.add(R.drawable.category_explore);
drawables.add(R.drawable.category_move);
drawables.add(R.drawable.category_party);
drawables.add(R.drawable.category_whatever);
mListView = (ListView) view.findViewById(R.id.filter_list);
filterAdapter = new FilterAdapter(view.getContext(), l, drawables);
mListView.setAdapter(filterAdapter);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Bebas = Typeface.createFromAsset(view.getContext().getAssets(), "fonts/BebasNeue.otf");
TextView mainHeader = (TextView) view.findViewById(R.id.filters_text);
mainHeader.setTypeface(Bebas);
SearchView filter_categories = (SearchView) view.findViewById(R.id.filter_categories);
int searchImgID = getResources().getIdentifier("android:id/search_button", null, null);
ImageView searchViewHint = (ImageView) filter_categories.findViewById(searchImgID);
searchViewHint.setImageResource(R.drawable.ab_icon_search);
int searchPlateID = filter_categories.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlateView = filter_categories.findViewById(searchPlateID);
if (searchPlateView != null) {
searchPlateView.setBackgroundResource(R.drawable.search_location_shape);
}
int searchViewID = filter_categories.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) filter_categories.findViewById(searchViewID);
textView.setTextColor(Color.GRAY);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.check_box);
return view;
}
private void save() {
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt("first", checkboxes.size());
for (int i = 0; i < checkboxes.size(); i++) {
editor.remove("Status_" + i);
editor.putInt("Status_" + i, checkboxes.get(i));
}
editor.commit();
}
private void load() {
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
int size = sharedPreferences.getInt("first", 0);
for (int i = 0; i < size; i++) {
checkboxes.add(sharedPreferences.getInt("Status_" + i, 0));
}
}
#Override
public void onPause() {
super.onPause();
save();
}
#Override
public void onResume() {
super.onResume();
load();
}
}
Layout I'm inflating for Adapter:
<?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">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECF0F1">
<ImageView
android:id="#+id/category_picture"
android:layout_width="70dp"
android:layout_height="60dp"
android:background="#drawable/sm_profile"/>
<TextView
android:id="#+id/filter_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/category_picture"
android:padding="10dp"
android:text="Party"
android:textColor="#color/enloop_dark_gray"
android:textSize="18dp"/>
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="10dp"/>
</RelativeLayout>
</RelativeLayout>
Instead of using OnItemClickListener in CheckinFilters.java, you should add that code in getView() method of FilterAdapter. You are actually adding checkbox for every row but the id for all checkbox is same, so you can't apply customized code for every checkbox.
To be able to make use of all checkboxes you can put checkbox code in getView() method because it also contains an argument called position. So you can just get the position and apply OnItemClickListener to every single checkbox. That way it will work.
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
#Override
public int getCount() {
return mFilters.size();
}
#Override
public Object getItem(int position) {
return mFilters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
if(position == 0) {
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
else {
}
}
});
}
//Similarly add OnClickListener to other checkboxes.
return convertView;
}
}
I'm trying to make a task manager, and I only have one problem. I have a listview that gets inflated. All the elements in the listview are correct. The problem is that when I select an item, the listview will select another item away. I've heard listviews repopulate the list as it scrolls down to save memory. I think this may be some sort of problem. Here is a picture of the problem.
If i had more apps loaded, then it would continue to select multiple at once.
Here is the code of my adapter and activity and XML associated
public class TaskAdapter extends BaseAdapter{
private Context mContext;
private List<TaskInfo> mListAppInfo;
private PackageManager mPack;
public TaskAdapter(Context c, List<TaskInfo> list, PackageManager pack) {
mContext = c;
mListAppInfo = list;
mPack = pack;
}
#Override
public int getCount() {
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
}
});
return convertView;
public class TaskManager extends Activity implements Runnable
{
private ProgressDialog pd;
private TextView ram;
private String s;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskpage);
setTitleColor(Color.YELLOW);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run()
{
//System.out.println("In Taskmanager Run() Thread");
final PackageManager pm = getPackageManager();
final ListView box = (ListView) findViewById(R.id.cBoxSpace);
final List<TaskInfo> CK = populate(box, pm);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
ram.setText(s);
box.setAdapter(new TaskAdapter(TaskManager.this, CK, pm));
//System.out.println("In Taskmanager runnable Run()");
endChecked(CK);
}
});
handler.sendEmptyMessage(0);
}
Taskinfo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/tmImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:scaleType="centerCrop"
android:adjustViewBounds="false"
android:focusable="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tmbox"
android:lines="2"/>
</LinearLayout>
Taskpage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/cBoxSpace"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/RAM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
<Button
android:id="#+id/endButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="End Selected Tasks" />
</LinearLayout>
Any ideas for what reason mutliple items are selected with a single click would be GREATLY appreciated. I've been messing around with different implementations and listeners and listadapters but to no avail.
I think the point is you only save checking state in the view(v.setSelected).
And you reuse these view, so its checkbox is always not change its state.
You can create a state array to save every checking state of every TaskInfo, and check this array when you create a view.
for example
// default is false
ArrayList<Boolean> checkingStates = new ArrayList<Boolean>(mListAppInfo.size());
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(checkingStates.get(position));
convertView.setSelected(checkingStates.get(position));
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
checkingStates.get(position) = false;
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
checkingStates.get(position) = true;
}
}
});
return convertView;
}
I'm not 100% sure what you are trying to do, but part of your problem might be related to the condition in your onClick method:
if(v.isSelected())
I think you want that to read
if(v.isChecked())
isSelected is inherited from View, and it means something different from isChecked
Also, the whether the CheckBox is checked or not is independent from your data model since it is a recycled view. Your CheckBox should be checked based on entry (I'm assuming your TextInfo class has an isChecked() method that returns a boolean:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(entry.isChecked());
}
I don't think you need the View.OnClickListener you are attaching to convertView. You should handle that in the OnItemClickListener attached to the ListView. Assuming your ListView is called listView and TaskInfo instances have setChecked and isChecked methods:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
entry = mListAppInfo.get(position);
entry.setChecked(!entry.isChecked());
}
});
First of all don't set the list checked or unchecked on view position.
because view position means only visible items position in your listview but you would like to set checked or uncheked status on a particular list item.
That's why this problem arises in your code.
You have the need to set the items checked and unchecked on your custom arraylist getter setter like the code i have attached below:
package com.app.adapter;
public class CategoryDynamicAdapter {
public static ArrayList<CategoryBean> categoryList = new ArrayList<CategoryBean>();
Context context;
Typeface typeface;
public static String videoUrl = "" ;
Handler handler;
Runnable runnable;
// constructor
public CategoryDynamicAdapter(Activity a, Context context, Bitmap [] imagelist,ArrayList<CategoryBean> list) {
this.context = context;
this.categoryList = list;
this.a = a;
}
// Baseadapter to the set the data response from web service into listview.
public BaseAdapter mEventAdapter = new BaseAdapter() {
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return categoryList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView title,category,uploadedBy;
ImageView image;
RatingBar video_rating;
Button report_video ,Flag_video;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder vh = null ;
if(convertView == null) {
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate (R .layout.custom_category_list_layout,null,false);
vh.title = (TextView) convertView .findViewById (R.id.title);
vh.image = (ImageView) convertView.findViewById(R.id.Imagefield);
convertView.setTag(vh);
}
else
{
vh=(ViewHolder) convertView.getTag();
}
try
{
final CategoryBean Cb = categoryList.get(position);
//pay attention to code below this line i have shown here how to select a listview using arraylist getter setter objects
String checkedStatus = Cb.getCheckedStringStaus();
if(checkdStatus.equal("0")
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else ////checkdStatus.equal("1")
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
catch (Exception e)
{
e.printStackTrace();
}