Listview not behaving well with Folding Cell Library - java

I have a problem using folding cell library from the RAMOTION
I have implemented everything but I am facing a problem with the list view
I have a list of planets and when user tap on let's say Jupiter the view gets unfolded and more information is visible to the user and when user tap on the same view which is seeing then the view gets folded
Problem
if the user scrolls down the list and then scroll back up and come back up to Jupiter the view remains unfolded and it is happening to all the view.
I appreciate if anyone helps me out
folding state
here
unfolding state
here
AdapterClass
#SuppressWarnings({"WeakerAccess", "unused"})
public class SolarSystemFoldingCellListAdapter extends ArrayAdapter<SolarSystemItemFoldingCell> {
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;
private int incomingPosition ;
public SolarSystemFoldingCellListAdapter(Context context, List<SolarSystemItemFoldingCell> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
// get item for selected view
SolarSystemItemFoldingCell solarSystemItemFoldingCell = getItem(position);
// if cell is exists - reuse it, if not - create the new one from resource
FoldingCell cell = (FoldingCell) convertView;
final ViewHolder viewHolder;
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.solar_system_folding_cell, parent, false);
// binding view parts to view holder
viewHolder.foldingCell = cell.findViewById(R.id.folding_cell);
viewHolder.relativeLayoutFolded = cell.findViewById(R.id.relativeLayoutFolded);
viewHolder.linearLayoutFolded = cell.findViewById(R.id.linearLayoutFolded);
viewHolder.planetOrStarNameFolded = cell.findViewById(R.id.planetOrStarNameFolded);
viewHolder.mass = cell.findViewById(R.id.mass);
viewHolder.actualMass = cell.findViewById(R.id.actualMass);
viewHolder.distance = cell.findViewById(R.id.distance);
viewHolder.actualDistance = cell.findViewById(R.id.actualDistance);
viewHolder.diameter = cell.findViewById(R.id.diameter);
viewHolder.actualDiameter = cell.findViewById(R.id.actualDiameter);
viewHolder.speed = cell.findViewById(R.id.speed);
viewHolder.actualSpeed = cell.findViewById(R.id.actualSpeed);
viewHolder.moreInfoButton = cell.findViewById(R.id.button);
viewHolder.frameLayoutUnfolded = cell.findViewById(R.id.frameLayoutUnfolded);
viewHolder.planetOrStarNameUnfolded = cell.findViewById(R.id.planetOrStarNameUnfolded);
cell.setTag(viewHolder);
} else {
// for existing cell set valid valid state(without animation)
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
} else {
cell.fold(true);
}
viewHolder = (ViewHolder) cell.getTag();
}
if (null == solarSystemItemFoldingCell)
return cell;
// bind data from selected element to view through view holder
viewHolder.planetOrStarNameFolded.setText(solarSystemItemFoldingCell.getPlantOrStarNameFolded());
viewHolder.actualMass.setText(solarSystemItemFoldingCell.getActualMass());
viewHolder.actualDistance.setText(solarSystemItemFoldingCell.getActualDistance());
viewHolder.actualDiameter.setText(solarSystemItemFoldingCell.getActualDiameter());
viewHolder.actualSpeed.setText(solarSystemItemFoldingCell.getActualSpeed());
viewHolder.planetOrStarNameUnfolded.setText(String.valueOf(solarSystemItemFoldingCell.getPlanetOrStarNameUnfolded()));
//setting Fonts
viewHolder.planetOrStarNameFolded.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.mass.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.distance.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.diameter.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.speed.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.actualMass.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDistance.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDiameter.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualSpeed.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.moreInfoButton.setTypeface(App.getAppInstance().getArvoRegular());
// set custom btn handler for list item from that item
if (solarSystemItemFoldingCell.getRequestBtnClickListener() != null) {
viewHolder.moreInfoButton.setOnClickListener(solarSystemItemFoldingCell.getRequestBtnClickListener());
} else {
// (optionally) add "default" handler if no handler found in item
viewHolder.moreInfoButton.setOnClickListener(defaultRequestBtnClickListener);
}
viewHolder.relativeLayoutFolded.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Something gets clicked", Toast.LENGTH_SHORT).show();
viewHolder.foldingCell.fold(false);
registerFold(incomingPosition);
}
});
return cell;
}
// simple methods for register cell state changes
public void registerToggle(int position) {
if (unfoldedIndexes.contains(position)) {
registerFold(position);
incomingPosition = position;
}else
registerUnfold(position);
}
public void registerFold(int position) {
unfoldedIndexes.remove(position);
}
public void registerUnfold(int position) {
unfoldedIndexes.add(position);
}
public View.OnClickListener getDefaultRequestBtnClickListener() {
return defaultRequestBtnClickListener;
}
public void setDefaultRequestBtnClickListener(View.OnClickListener defaultRequestBtnClickListener) {
this.defaultRequestBtnClickListener = defaultRequestBtnClickListener;
}
// View lookup cache
private static class ViewHolder {
RelativeLayout relativeLayoutFolded ;
LinearLayout linearLayoutFolded ;
TextView planetOrStarNameFolded;
TextView mass;
TextView actualMass;
TextView distance;
TextView actualDistance;
TextView diameter;
TextView actualDiameter;
TextView speed;
TextView actualSpeed ;
Button moreInfoButton ;
FrameLayout frameLayoutUnfolded ;
TextView planetOrStarNameUnfolded;
FoldingCell foldingCell ;
}
}
SolarSystemClass
private void listViewIntegration (){
arrayList = addingDataIntoList();
solarSystemFoldingCellListAdapter = new SolarSystemFoldingCellListAdapter(SolarSystem.this , arrayList);
listView.setAdapter(solarSystemFoldingCellListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int duration = 500; //miliseconds
int offset = 0; //fromListTop
listView.smoothScrollToPositionFromTop(position,offset,duration);
// toggle clicked cell state
((FoldingCell) view).toggle(false);
// register in adapter that state for selected cell is toggled
solarSystemFoldingCellListAdapter.registerToggle(position);
// listView.smoothScrollToPosition(position);
}
});
}

Related

No Action while SmoothScrollToPosition in Custom List View

Hi I m using below code where when user touches the textview , list will be updated and touched list row will be in front of user.
public class AppAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<AppList> listStorage;
private Context context;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
int pos = 0;
public AppAdapter(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.context = context;
}
#Override
public int getCount() {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
pos = sharedPreferences.getInt("pos", 0);
Log.e("POS",pos+"At Get cpiunt");
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.textInListView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("pos", position).apply();
Log.e("Pressed", position + "");
MainActivity.installedAppAdapter.notifyDataSetChanged();
Log.e("Saved", sharedPreferences.getInt("pos", 0) + "value");
}
});
if (pos != 0) {
MainActivity.userInstalledApps.setSelection(pos);
editor.putInt("pos",0).apply();
}
return convertView;
}
static class ViewHolder {
TextView textInListView;
ImageView imageInListView;
}
}
I read many questions but did not get clear picture about how to use SmoothScrolltopostion. Though I as per info got, I captured click position and retrieved during list load to set saved position of list to user.
If I use smoothscrolltoposition, there is no action, but if I use setselection as shown in above code, I could able to see the clicked item in top of view after reloading.
Why smoothscroll is not working and m I doing correct coding for required action. pls guide.

All values in RecycleView and ListView are changing while I'm using dialog

I have a dialog and I want to add a recyclerView or listView and I know that I have to use a List to control items in each row. Now when I want to change a value of a checkbox or a radioButton all the data in List are changing. I used Log and I got that all the booleans data changed at the same time. I moved all items to an activity but the problem still remains. It seems there is a link between the arrayList data.
Also I changed my codes and used SwitchCompat but all Boolean data in mDataSet are changing when I want to change just one of them.
public class AdapterSetOnOffTime extends RecyclerView.Adapter<AdapterSetOnOffTime.ViewHolder> {
private Context mContext;
private ArrayList<StructSetOnOffTime> mDataSet;
private View mView;
public AdapterSetOnOffTime(Context context, ArrayList<StructSetOnOffTime> dataSet) {
mContext = context;
mDataSet = dataSet;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int id = R.layout.layout_list_settime_items;
mView = LayoutInflater.from(mContext).inflate(id, parent, false);
return new ViewHolder(mView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mSwitch.setChecked(mDataSet.get(position).setOnOffValue);
holder.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
mDataSet.get(position).setOnOffValue = true;
}else{
mDataSet.get(position).setOnOffValue = false;
}
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextTitle;
public TextView mTextValue;
public ImageButton mBtn;
public SwitchCompat mSwitch;
public ViewHolder(View itemView) {
super(itemView);
mTextTitle = (TextView) itemView.findViewById(R.id.txtSetTime);
mTextValue = (TextView) itemView.findViewById(R.id.txtOnOffStatus);
mBtn = (ImageButton) itemView.findViewById(R.id.btnSetTime);
mSwitch = (SwitchCompat) itemView.findViewById(R.id.swPrefSwitch);
}
}
}
Update answer
After wasting a day I recognized that I made a little mistake to fill ArrayList and I'm going to share it.
Previous method of fill adapter:
StructSetOnOffTime item = new StructSetOnOffTime();
ArrayList<StructSetOnOffTime> arrayList = new ArrayList<>();
for(int i = 0; i < 9; i++){
item.setTimeValue = null;
item.setOnOffValue = false;
arrayList.add(item);
}
As #Anatoli said, I had a problem in this section and I solved it by changing the upper method to this one:
ArrayList<StructSetOnOffTime> arrayList = new ArrayList<>();
for(int i = 0; i < 9; i++){
StructSetOnOffTime item = new StructSetOnOffTime();
item.setTimeValue = null;
item.setOnOffValue = false;
arrayList.add(item);
}
You set to radOn and radOff same OnCheckedChangeListener and checks in listener if it was set to true. Why you don't make 2 listeners?
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).onOffStatus = true;
// update adapter
notifyDataSetChanged();
}
}
};
holder.radOn.setOnCheckedChangeListener(listener);
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).onOffStatus = false;
// update adapter
notifyDataSetChanged();
}
}
};
holder.radOff.setOnCheckedChangeListener(listener);
looks much simpler
calling of
holder.radOn.setChecked(holder.radOn == buttonView);
holder.radOff.setChecked(holder.radOff == buttonView);
triggers the listeners. To update values in list, just call adapter.notifyDataSetChanged();
UPDATE
For each new item in list you must initialize new Holder
RecyclerView
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
// Inflate the custom layout
View itemView = LayoutInflater.from(parent.getContext())
.inflate(layoutId, parent, false);
return new Holder(itemView, viewType);
}
ArayList
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
Holder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new Holder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (Holder) convertView.getTag();
}
Item item = getItem(position);
fill(item, position);
return convertView;
}
When ever you set the check state of your view(from your code also if view didn't get destroyed) your check listener will get called so you need to manually maintain the state. It will work for all radiobutton, checkbox etc.
holder.mSwitch.setOnCheckedChangeListener(null);
holder.mSwitch.setChecked(mDataSet.get(position).setOnOffValue);
holder.mSwitch.setOnClickListener(new OnClickListener(){
//holder.mSwitch.setCheck(!mDataSet.get(position).setOnOffValue);
mDataSet.get(position).setOnOffValue = !mDataSet.get(position).setOnOffValue;
});

Change all ImageViews in ListView to a particular image

I'm trying to make an audio file preview page which consists of a listview of files in a folder. Each row has a play button next to it which changes to a stop button when clicked. I now need a way of setting all the other images to the play button if a row is clicked as only one audio file should be playing at once. I tried iterating through the list and getting the imageview from this but had no luck (shown below):
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
IncidentLogger logger = new IncidentLogger(this.getActivity());
final List<Audio> audioList = logger.getAllAudio();
AudioListViewAdapter adapter = new AudioListViewAdapter(audioList, getActivity());
final ListView listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
OnItemClickListener onItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i = 0; i < audioList.size(); i++) {
View v = listView.getAdapter().getView(i, view, parent);
ImageView imageView = (ImageView) v.findViewById(R.id.control);
imageView.setImageResource(R.drawable.ic_action_play);
}
ImageView iv = (ImageView) view.findViewById(R.id.control);
if(iv.getTag() == "1") {
iv.setTag("0");
iv.setImageResource(R.drawable.ic_action_play);
} else {
iv.setTag("1");
iv.setImageResource(R.drawable.ic_action_stop);
}
}
};
listView.setOnItemClickListener(onItemClickListener);
}
This can be done so easily, you need to just look at on the position of list item that was clicked by user. A well described complete demo code is as below ...
public class ChangeImageInListDynamically extends Activity {
/**
* Adapter for your data.
*/
ImageAdapter adpAR;
ArrayList<String> itemList;
ListView mListView;
ImageAdapter mAdapter;
/**
* Indicate which item is currently selected.
* Its default selected item is '0' e.g., 1st item.
*/
private int selectedPosition=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
itemList = new ArrayList<String>();
for (int i = 0; i < 11; i++) {
itemList.add("Item - "+i);
}
mListView = (ListView)findViewById(R.id.data_list);
//Initialize your adapter
mAdapter = new ImageAdapter(nChangeImageInListDynamically.this, itemList);
//set adapter to your list.
mListView.setAdapter(mAdapter);
//set list click listener.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
//your image that need to change dynamically.
ImageView imageView = (ImageView) view.findViewById(R.id.select);
//position of clicked item.
selectedPosition=position;
//change image of respective image.
imageView.setImageResource(R.drawable.selected);
//notify your adapter to update your list.
adpAR.notifyDataSetChanged();
}
});
}
static class ViewHolder {
TextView title;
ImageView img;
}
/**
* Your ImageAdapter.
*/
public class ImageAdapter extends BaseAdapter {
ArrayList<String> dataList;
Context context;
public ImageAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.dataList = arrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return dataList.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) {
View row = convertView;
final ViewHolder holder;
Log.d("posiiton ImageAdapater : ",""+position);
if (row == null) {
LayoutInflater inflater = ChangeImageInListDynamically.this.getLayoutInflater();
row = inflater.inflate(R.layout.listrow, null);
holder = new ViewHolder();
holder.title = (TextView) row.findViewById(R.id.text);
holder.img = (ImageView) row.findViewById(R.id.select);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
//set titel text.
holder.title.setText(dataList.get(position));
//Change Image of selected item dynamically.
if(selectedPosition == position) {
//Item is selected.
holder.img.setImageResource(R.drawable.selected);
}else{
//Other non-selected items.
holder.img.setImageResource(R.drawable.dis_selected);
}
return row;
}
}
}

Custom multiselected listview Android

I have been trying create a multiselected ListView like it looks on picture in this link:
picture
When user unchecked the checkbox in the top-left corner listviewItem layout must be changed to unchecked state.
Now I use it:
public class ProcedureAdapter : BaseAdapter<Procedure>
{
List<Procedure> items;
Activity context;
Dictionary<int, bool> CheckedItems = new Dictionary<int, bool>();
public ProcedureAdapter(Activity context, List<Procedure> items)
: base()
{
this.context = context;
this.items = items;
for (int i = 0; i < items.Count; i++)
{
CheckedItems.Add(i, false);
}
}
public override long GetItemId(int position)
{
return position;
}
public override Procedure this[int position]
{
get { return items[position]; }
}
public override int Count
{
get { return items.Count; }
}
public void toggleCheck(int position)
{
if (CheckedItems.ContainsKey(position))
{
CheckedItems[position] = !CheckedItems[position];
base.NotifyDataSetChanged();
}
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = items[position];
View view = convertView;
if (view == null)
view = context.LayoutInflater.Inflate(Resource.Layout.ProcedureListViewItem, null);
if (!CheckedItems.ContainsKey(position))
CheckedItems.Add(position, false);
if (CheckedItems[position])
{
checkBox.Visibility = ViewStates.Visible;
checkBox.Checked = true;
ProcedureTypeImage.Visibility = ViewStates.Gone;
}
else
{
checkBox.Visibility = ViewStates.Gone;
checkBox.Checked = false;
ProcedureTypeImage.Visibility = ViewStates.Visible;
}
return view;
}
}
In the activity:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.ProceduresLayout, container, false);
listView = view.FindViewById<ListView>(Resource.Id.listView1);
listView.ItemLongClick += listView_ItemLongClick;
procAdapter = new ProcedureAdapter(Activity, procedures);
listView.Adapter = procAdapter;
return view;
}
void listView_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
{
procAdapter.toggleCheck(e.Position);
}
but i faced with problem:
how can I change layout when user unchecked the checkbox?
I have tried processing CheckedChange event in the Adapter, but how I will know position of this ListViewItem?
My solution seems to me not very good, please give me advice how can I do it better.
I was wondering if you show to me a simple example on C# or Java.
Thanks
I made a simple example that might help you. It's a list and each list item has a TextView and CheckBox. Text view is showing position in green or red color depending on if check box checked or not. It is simplified version of your problem. Don't know if it's best solution but it will work.
Only thing to note. Since views are being reused when you bind check box it can trigger CheckedChange event. That is why Tag is first changed when doing the binding.
using System.Globalization;
using Android.App;
using Android.Graphics;
using Android.Views;
using Android.Widget;
using Object = Java.Lang.Object;
namespace AndroidApplication1
{
public class LvAdapter : BaseAdapter
{
private readonly Activity _context;
public bool[] Bools = new bool[15];
public LvAdapter(Activity context)
{
_context = context;
}
public override Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
ViewHolder vh;
var view = convertView;
if (view == null)
{
view = _context.LayoutInflater.Inflate(Resource.Layout.list_item, parent, false);
vh = new ViewHolder();
vh.Initialize(view, this);
view.Tag = vh;
}
vh = view.Tag as ViewHolder;
if (vh != null) vh.Bind(position, Bools);
return view;
}
public override int Count
{
get { return Bools.Length; }
}
private class ViewHolder : Object
{
private TextView _text;
private CheckBox _check;
public void Initialize(View view, LvAdapter adapter)
{
_text = view.FindViewById<TextView>(Resource.Id.tvText);
_check = view.FindViewById<CheckBox>(Resource.Id.cbCheck);
_check.CheckedChange += (sender, args) =>
{
var tagHoldr = (((View) sender).Tag) as TagHolder;
adapter.Bools[tagHoldr.Positon] = args.IsChecked;
tagHoldr.TextView.SetTextColor(args.IsChecked ? Color.Green : Color.Red);
};
}
public void Bind(int position, bool[] bools)
{
_check.Tag = new TagHolder { Positon = position, TextView = _text };
_text.Text = position.ToString(CultureInfo.InvariantCulture);
_check.Checked = bools[position];
_text.SetTextColor(bools[position] ? Color.Green : Color.Red);
}
}
private class TagHolder : Object
{
public int Positon { get; set; }
public TextView TextView { get; set; }
}
}
}

update listview from an Array adapter

I'm trying to refresh the list view when I click on a single item of the list view.
For example I'm trying to do something like this:
public class RssItemsAdapter extends ArrayAdapter<Item> {
private TextView txtTitle;
private ImageView imgFavourite;
private int resourceId;
private Context context;
private List<Item> items = new ArrayList<Item>();
public RssItemsAdapter(Context context, int resourceId, List<Item> items)
{
super(context, resourceId, items);
this.context = context;
this.items = items;
this.resourceId = resourceId;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Item getItem(int index) {
return items.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
Item item = getItem(position);
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(resourceId, parent, false);
}
txtTitle = (TextView) row.findViewById(R.id.title);
txtTitle.setText(item.getTitle());
imgFavourite = (ImageView) row.findViewById(R.id.favourite);
imgFavourite.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (item.isFavourite() == true) {
imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_off);
}
else {
imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_on);
}
}
});
// add a "star" icon on favourite items
if (item.isFavourite() == true)
imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_on);
else
imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_off);
return row;
}
Every time I click on the imgFavourite icon it should change. Where is the problem?
It doesn't look like you are ever changing the value of item.isFavourite(). Assuming you want to toggle when that item is clicked...
imgFavourite.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Toggle the current state
item.setIsFavourite(!item.isFavourite());
if (item.isFavourite() == true) {
imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_off);
}
else {
imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_on);
}
}
});
Also, you should be doing this kind of work in the ListView's onItemClickListsner. As is, this will create a new onClickListener each time a new row is brought into view. Beyond that, check into the "view holder pattern".

Categories