Display image Id instead of image in Android - android

I have a expandable recycler view which have some parent and some child items as like this.
I'm trying to add a image with every file name using like this code:
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, obj1.optString("category").trim()+" "+R.drawable.download48));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, obj1.optString("filename").trim()));
But it prints the image id(red circled area) instead of actual image. How to print here actual image?
Here is my adapter code:
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (type) {
case HEADER:
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
view = inflater.inflate(R.layout.listchild, parent, false);
ListChildViewHolder child = new ListChildViewHolder(view);
return child;
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
private static class ListChildViewHolder extends RecyclerView.ViewHolder {
public TextView header_title1;
public ImageView btn_expand_toggle1;
public Item refferalItem1;
public ListChildViewHolder(View itemView) {
super(itemView);
header_title1 = (TextView) itemView.findViewById(R.id.header_title1);
btn_expand_toggle1 = (ImageView) itemView.findViewById(R.id.btn_expand_toggle1);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}

Your onBindViewHolder() method's case CHILD should look something like this
case CHILD:
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
itemController1.btn_expand_toggle1.setImageResource(item.resId);
break;
And your class Item should be something like this:
public static class Item {
public int type;
public String text;
private int resId;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text, #DrawableRes int resId) {
this.type = type;
this.text = text;
this.resId = resId;
}
}
And while initializing it should be
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, obj1.optString("category").trim(), R.drawable.download48));

Add this line
btn_expand_toggle1.setImageDrawable(getResources().getDrawab‌​le(R.drawable.ic_lau‌​ncher));
after
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
It will work

Related

Specific View holder in recyclerView Adapter cant cast to View Holder

I use below code but its has an error:-
EventAdapter$MainViewHolder cannot be cast to EventAdapter$ProfileViewHolder
But each viewHolder extended from MainViewHolder,
where is problem in this code?
thanks guys, I am newcomer in stack overflow!
public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.MainViewHolder> {
List<MainOption> mainOptionlist;
Context context;
private static final int TYPE_PROFILE = 1;
private static final int TYPE_OPTION_MENU = 2;
public NavDrawerAdapter(Context context){
this.mainOptionlist = MainOption.getDrawableDataList();
this.context = context;
}
#Override
public int getItemViewType(int position) {
return (position == 0? TYPE_PROFILE : TYPE_OPTION_MENU);
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){}
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
if(holder.getItemViewType() == TYPE_PROFILE){
ProfileViewHolder mholder = (ProfileViewHolder) holder;
}
else {
MyViewHolder mHolder = (MyViewHolder) holder;
MainOption mo = mainOptionlist.get(position);
mHolder.tv_title.setText(mo.title);
}
}
#Override
public int getItemCount() {
return mainOptionlist.size();
}
public class MyViewHolder extends MainViewHolder{
public MyViewHolder(View v){
super(v);
}
}
public class ProfileViewHolder extends MainViewHolder{
public ProfileViewHolder(View v){
super(v);
}
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View v) {
super(v);
}
}
public class ChaptersAdapter extends BaseAdapter {
private static final int TYPE_CHAPTER = 0;
private static final int TYPE_PART = 1;
private Context mContext;
private ArrayList<Chapter> mChapters;
private LayoutInflater mInflater;
private ItemClickListener mItemClickListener;
private TreeSet<Integer> mSectionNumber = new TreeSet<Integer>();
private boolean mIsPaid;
public ChaptersAdapter(Context context, ArrayList<Chapter> chapters, ItemClickListener itemClickListener, boolean isPaid) {
mContext = context;
mChapters = chapters;
mItemClickListener = itemClickListener;
mInflater = LayoutInflater.from(context);
mIsPaid = isPaid;
saveSectionNum();
}
#Override
public int getCount() {
int n = 0;
for (int i = 0; i < mChapters.size(); i++) {
n += mChapters.get(i).mParts.size();
}
n += mChapters.size();
if (n < 0)
return 0;
return n;
}
private void saveSectionNum() {
int n = 0;
for (int i = 0; i < mChapters.size(); i++) {
mSectionNumber.add(n);
n += mChapters.get(i).mParts.size();
n++;
}
}
private ChapterPart getChapterPart(int position) {
int n = 0;
int chapterNum = 0;
int partNum = -1;
while ( n < position ) {
n++;
n += mChapters.get(chapterNum).mParts.size();
chapterNum++;
}
if ( n > position ) {
chapterNum--;
n = n - mChapters.get(chapterNum).mParts.size();
partNum = position - n;
} else if ( n == position) {
partNum = -1;
}
return new ChapterPart(chapterNum, partNum);
}
#Override
public int getItemViewType(int position) {
return mSectionNumber.contains(position) ? TYPE_CHAPTER : TYPE_PART;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Object getItem(int position) {
ChapterPart chapterPart = getChapterPart(position);
if (-1 == chapterPart.mPartNum) {
return mChapters.get(chapterPart.mChapterNum);
}
return mChapters.get(chapterPart.mChapterNum).mParts.get(chapterPart.mPartNum);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int rowType = getItemViewType(position);
if (convertView == null) {
switch (rowType) {
case TYPE_CHAPTER:
convertView = mInflater.inflate(R.layout.listitem_chapter, null);
ChapterTag tag1 = new ChapterTag(convertView);
convertView.setTag(tag1);
break;
case TYPE_PART:
convertView = mInflater.inflate(R.layout.listitem_part, null);
PartTag tag2 = new PartTag(convertView);
convertView.setTag(tag2);
break;
}
}
switch (rowType) {
case TYPE_CHAPTER:
ChapterTag tag1 = (ChapterTag)(convertView.getTag());
Chapter chapter = (Chapter)getItem(position);
tag1.setData(position, chapter);
break;
case TYPE_PART:
PartTag tag2 = (PartTag)(convertView.getTag());
Part part = (Part)getItem(position);
tag2.setData(position, part);
break;
}
return convertView;
}
class ChapterTag {
View view;
TextView txtChapter;
Chapter chapter;
public ChapterTag(final View view) {
this.view = view;
txtChapter = (TextView) view.findViewById(R.id.txt_chapter);
}
public void setData(int position, Chapter chapter) {
this.chapter = chapter;
txtChapter.setText(chapter.mName);
}
}
class PartTag {
View view;
TextView txtPart;
FancyButton btnVideo;
FancyButton btnAudio;
Part part;
public PartTag(final View view) {
this.view = view;
txtPart = (TextView) view.findViewById(R.id.txt_part);
btnVideo = (FancyButton) view.findViewById(R.id.btn_video);
UiUtil.applyButtonEffect(btnVideo, new Runnable() {
#Override
public void run() {
mItemClickListener.onVideoClick(part.mVideoURL);
}
});
btnAudio = (FancyButton) view.findViewById(R.id.btn_audio);
UiUtil.applyButtonEffect(btnAudio, new Runnable() {
#Override
public void run() {
mItemClickListener.onAudioClick(part.mAudioURL);
}
});
}
public void setData(int position, Part part) {
this.part = part;
txtPart.setText(part.mName);
if (part.mVideoURL.equals("")) {
btnVideo.setEnabled(false);
}
if (part.mAudioURL.equals("")) {
btnAudio.setEnabled(false);
}
ChapterPart chapterpart = getChapterPart(position);
if (position > 3 + chapterpart.mChapterNum && mIsPaid == false) {
btnVideo.setEnabled(false);
btnAudio.setEnabled(false);
}
}
}
class ChapterPart {
int mChapterNum;
int mPartNum;
ChapterPart(int chapterNum, int partNum) {
mChapterNum = chapterNum;
mPartNum = partNum;
}
}
}

Recyclerview holder setting an image text instead of drawable

I need your help to display the array texts as image, displaying them as text is working, but is image is not working. below are some explanation.
I have an array of texts that I want to display them in recycler view as an image.
String[] images =
{
"for_honor.png",
"R.drawable.ghost_recon.png",
"R.drawable.horizon_zerod.png",
"R.drawable.mass_effect.png"
};
setting them in this way seems wrong as i am not getting image
((MyViewHolder) holder).getmDataImgView().getResources().getIdentifier(name,"drawable","com.example.pkg.pg.Adapters");
however this code is working it show me them as text not image
// ((MyViewHolder) holder).getmDataTextView().setText(name);
this code im my main activity
MainGridRecView = (RecyclerView) findViewById(R.id.maingridrc);
MainGridRecViewLayoutManager = new LinearLayoutManager(context);
MainGridRecView.setLayoutManager(MainGridRecViewLayoutManager);
MainGridRecViewAdapter = new MainGridRvAdapter( dataHorizontal,dataVertical,MainActivity.this);
MainGridRecView.setAdapter(MainGridRecViewAdapter);
this maingridrvadapter
public class MainGridRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private ArrayList<ListMainItem> dataHorizontal;
private ArrayList<ListMainItem> dataVertical;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
public MainGridRvAdapter(ArrayList<ListMainItem> dataHorizontal, ArrayList<ListMainItem> dataVertical, Context context) {
setDataHorizontal(dataHorizontal);
setDataVertical(dataVertical);
mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
//inflate your layout and pass it to view holder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new MyViewHolder(v);
} else if (viewType == TYPE_HEADER) {
//inflate your layout and pass it to view holder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_header, parent, false);
return new MyViewHolderHeader(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof MyViewHolder) {
String name = getDataVertical().get(position-1).getImages();
Log.d("###", "Setting name: " + name);
((MyViewHolder) holder).getmDataImgView().getResources().getIdentifier(name,"drawable","com.example.pkg.pg.Adapters");
// int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
} else if (holder instanceof MyViewHolderHeader) {
//cast holder to VHHeader and set data for header.
Log.d("####", "HEADER");
}
}
#Override
public int getItemCount() {
return dataVertical.size() + 1;
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
}
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
public void setDataHorizontal(ArrayList<ListMainItem> dataHorizontal) {
this.dataHorizontal = dataHorizontal;
}
public ArrayList<ListMainItem> getDataHorizontal() {
return dataHorizontal;
}
public void setDataVertical(ArrayList<ListMainItem> dataVertical) {
this.dataVertical = dataVertical;
}
public ArrayList<ListMainItem> getDataVertical() {
return dataVertical;
}
private class MyViewHolder extends RecyclerView.ViewHolder {
// private final TextView mDataTextView;
private final ImageView mDataImgView;
public MyViewHolder(View v) {
super(v);
// mDataTextView = (TextView) v.findViewById(R.id.data_vertical);
mDataImgView = (ImageView) v.findViewById(R.id.img_vertical);
}
/*
public TextView getmDataTextView() {
return mDataTextView;
}*/
public ImageView getmDataImgView() {
return mDataImgView;
}
}
private class MyViewHolderHeader extends RecyclerView.ViewHolder {
private final RecyclerView mHorizontalRecyclerView;
public MyViewHolderHeader(View v) {
super(v);
mHorizontalRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view_horizontal);
RecyclerViewAdapterHorizontal mAdapter = new RecyclerViewAdapterHorizontal(getDataHorizontal());
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
mHorizontalRecyclerView.setLayoutManager(layoutManager);
mHorizontalRecyclerView.setAdapter(mAdapter);
}
}
}
layout
<TextView
android:id="#+id/data_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"
/>
<ImageView
android:id="#+id/img_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
class RecyclerViewAdapterHorizontal extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final ArrayList<ListMainItem> mData;
private final Context mContext;
public RecyclerViewAdapterHorizontal(ArrayList<ListMainItem> dataHorizontal,Context context) {
mData = dataHorizontal;
mContext=context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new RecyclerViewAdapterHorizontal.MyViewHolderHeader(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
String name = mData.get(position).getImages();
Log.d("###", "Setting name: " + name);
// ((RecyclerViewAdapterHorizontal.MyViewHolderHeader) holder).getmDataTextView().setText(name);
((RecyclerViewAdapterHorizontal.MyViewHolderHeader) holder).getmDataImgView().setImageResource(mContext.getResources().getIdentifier(name, "drawable", "com.example.mohamadmouazen.lebgame.Adapters"));
}
#Override
public int getItemCount() {
return mData.size();
}
private class MyViewHolderHeader extends RecyclerView.ViewHolder {
// private final TextView mDataTextView;
private final ImageView mDataImgView;
public MyViewHolderHeader(View v) {
super(v);
// mDataTextView = (TextView) v.findViewById(R.id.data_vertical);
mDataImgView = (ImageView) v.findViewById(R.id.img_vertical);
}
public ImageView getmDataImgView() {
return mDataImgView;
}
/* public TextView getmDataTextView() {
return mDataTextView;
}*/
}
edit
class RecyclerViewAdapterHorizontal extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final ArrayList<ListMainItem> mData;
private final Context mContext;
public RecyclerViewAdapterHorizontal(ArrayList<ListMainItem> dataHorizontal,Context context) {
mData = dataHorizontal;
mContext=context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new RecyclerViewAdapterHorizontal.MyViewHolderHeader(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
String name = mData.get(position).getImages();
Log.d("###", "Setting name: " + name);
// ((RecyclerViewAdapterHorizontal.MyViewHolderHeader) holder).getmDataTextView().setText(name);
((RecyclerViewAdapterHorizontal.MyViewHolderHeader) holder).getmDataImgView().setImageResource(mContext.getResources().getIdentifier(name, "drawable", "com.example.pkg.pg.Adapters"));
}
#Override
public int getItemCount() {
return mData.size();
}
private class MyViewHolderHeader extends RecyclerView.ViewHolder {
// private final TextView mDataTextView;
private final ImageView mDataImgView;
public MyViewHolderHeader(View v) {
super(v);
// mDataTextView = (TextView) v.findViewById(R.id.data_vertical);
mDataImgView = (ImageView) v.findViewById(R.id.img_vertical);
}
public ImageView getmDataImgView() {
return mDataImgView;
}
/* public TextView getmDataTextView() {
return mDataTextView;
}*/
}
}
Change your images array to ints:
int[] images = {
R.drawable.for_honor,
R.drawable.ghost_recon,
R.drawable.horizon_zerod,
R.drawable.mass_effect
};
and set the image something like so:
int resourceId = images[position]; // <-- apply your actual logic here
...getmDataImgView().setImageResource(resourceId);
A method int getIdentifier (String name, String defType, String defPackage) returns resource identifier for the given resource name. In other words it returns the R.drawable.your_name .
When you set the text it works because TextView is expecting the String type.
Plus you actually do not set anything to your ImageView. Your mistake is here:
((MyViewHolder) holder).getmDataImgView().getResources().getIdentifier(name,"drawable","com.example.pkg.pg.Adapters");
You just getting the identifier from the resource. Instead to set the image you should do:
((MyViewHolder) holder).getmDataImgView().setImageResource(mContext.getResources().getIdentifier(name,"drawable","com.example.pkg.pg.Adapters"));
By the way it is not reccomended to hardcode your resources names in the string. Do it in the proper way by setting resource identifier directly.

How to sort items in RecyclerView depending on a Date

This is what my screen should look like.
I added this library https://github.com/ShamylZakariya/StickyHeaders and tried to do it in similar way.
My model looks like this:
public class Transaction {
private int id;
private Date createdDate;
private String description;
private int amount;
private float newCredits;
}
and
public class Transactions {
private int totalCount;
private List<Transaction> transactions = new ArrayList<>();
}
So after i fetch all my transactions I set the data in adapter.. this is what my adapter looks like:
public class WalletAdapter extends SectioningAdapter {
private static final boolean USE_DEBUG_APPEARANCE = false;
private Transactions transactions;
private List<Section> sections = new ArrayList<>();
public WalletAdapter() {
}
private class Section {
String alpha;
Transactions transactions;
}
public Transactions getTransactions() {
return transactions;
}
public void setTransactions(Transactions transactions) {
this.transactions = transactions;
sections.clear();
char alpha = 0;
Section currentSection = null;
for (Transaction transaction : transactions.getTransactions()) {
String date = parseDate(transaction.getCreatedDate());
if (date.charAt(0) != alpha) {
if (currentSection != null) {
sections.add(currentSection);
}
currentSection = new Section();
alpha = date.charAt(0);
currentSection.alpha = String.valueOf(alpha);
}
if (currentSection != null) {
currentSection.transactions = this.transactions;
}
}
sections.add(currentSection);
notifyAllSectionsDataSetChanged();
}
private String parseDate(Date date) {
DateFormat df = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault());
String formattedDate = "";
formattedDate = df.format(date);
return formattedDate;
}
#Override
public int getNumberOfSections() {
return sections.size();
}
#Override
public boolean doesSectionHaveHeader(int sectionIndex) {
return true;
}
#Override
public boolean doesSectionHaveFooter(int sectionIndex) {
return false;
}
#Override
public int getNumberOfItemsInSection(int sectionIndex) {
return sections.get(sectionIndex).transactions.getTransactions().size();
}
#Override
public ItemViewHolder onCreateItemViewHolder(ViewGroup parent, int itemUserType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.wallet_item, parent, false);
return new ItemViewHolder(v);
}
#Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent, int headerUserType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.wallet_header, parent, false);
return new HeaderViewHolder(v);
}
#Override
public void onBindItemViewHolder(SectioningAdapter.ItemViewHolder viewHolder, int sectionIndex, int itemIndex, int itemType) {
Section section = sections.get(sectionIndex);
ItemViewHolder holder = (ItemViewHolder) viewHolder;
Transaction transaction = section.transactions.getTransactions().get(itemIndex);
holder.description.setText(transaction.getDescription());
holder.ammount.setText(String.valueOf(transaction.getAmount()));
holder.time.setText(parseDate(transaction.getCreatedDate()));
holder.total.setText(String.valueOf(transaction.getNewCredits()));
}
#Override
public void onBindHeaderViewHolder(SectioningAdapter.HeaderViewHolder viewHolder, int sectionIndex, int headerType) {
Section s = sections.get(sectionIndex);
HeaderViewHolder hvh = (HeaderViewHolder) viewHolder;
Transaction transaction = s.transactions.getTransactions().get(sectionIndex);
if (USE_DEBUG_APPEARANCE) {
hvh.itemView.setBackgroundColor(0x55ffffff);
hvh.dateHeader.setText(pad(sectionIndex * 2) + s.alpha);
} else {
hvh.dateHeader.setText(parseDate(transaction.getCreatedDate()));
}
}
private String pad(int spaces) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < spaces; i++) {
b.append(' ');
}
return b.toString();
}
public class HeaderViewHolder extends SectioningAdapter.HeaderViewHolder {
TextView dateHeader;
public HeaderViewHolder(View itemView) {
super(itemView);
dateHeader = (TextView) itemView.findViewById(R.id.date);
}
}
public class ItemViewHolder extends SectioningAdapter.ItemViewHolder {
TextView description;
TextView time;
TextView ammount;
TextView total;
public ItemViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.description);
time = (TextView) itemView.findViewById(R.id.time);
ammount = (TextView) itemView.findViewById(R.id.ammount);
total = (TextView) itemView.findViewById(R.id.new_credits);
}
}
}
So if I do it this way, It sorts and creates headers/sections by date, but it puts all transactions in all sections, not inside matching date...
Seems like this should handle if item should have header or no. Smth like, if it is first item with this date return true, if not - false.
#Override
public boolean doesSectionHaveHeader(int sectionIndex) {
return true;
}
EDIT:
You can make filtered list before setting it.
For example for address book with name letter header:
public class AddressBookDemoAdapter extends SectioningAdapter {
Locale locale = Locale.getDefault();
static final boolean USE_DEBUG_APPEARANCE = false;
private class Section {
String alpha;
ArrayList<Person> people = new ArrayList<>();
}
public class ItemViewHolder extends SectioningAdapter.ItemViewHolder {
TextView personNameTextView;
public ItemViewHolder(View itemView) {
super(itemView);
personNameTextView = (TextView) itemView.findViewById(R.id.personNameTextView);
}
}
public class HeaderViewHolder extends SectioningAdapter.HeaderViewHolder {
TextView titleTextView;
public HeaderViewHolder(View itemView) {
super(itemView);
titleTextView = (TextView) itemView.findViewById(R.id.titleTextView);
}
}
List<Person> people;
ArrayList<Section> sections = new ArrayList<>();
public AddressBookDemoAdapter() {
}
public List<Person> getPeople() {
return people;
}
public void setPeople(List<Person> people) {
this.people = people;
sections.clear();
// sort people into buckets by the first letter of last name
char alpha = 0;
Section currentSection = null;
for (Person person : people) {
if (person.name.last.charAt(0) != alpha) {
if (currentSection != null) {
sections.add(currentSection);
}
currentSection = new Section();
alpha = person.name.last.charAt(0);
currentSection.alpha = String.valueOf(alpha);
}
if (currentSection != null) {
currentSection.people.add(person);
}
}
sections.add(currentSection);
notifyAllSectionsDataSetChanged();
}
#Override
public int getNumberOfSections() {
return sections.size();
}
#Override
public int getNumberOfItemsInSection(int sectionIndex) {
return sections.get(sectionIndex).people.size();
}
#Override
public boolean doesSectionHaveHeader(int sectionIndex) {
return true;
}
#Override
public boolean doesSectionHaveFooter(int sectionIndex) {
return false;
}
#Override
public ItemViewHolder onCreateItemViewHolder(ViewGroup parent, int itemType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_item_addressbook_person, parent, false);
return new ItemViewHolder(v);
}
#Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent, int headerType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_item_addressbook_header, parent, false);
return new HeaderViewHolder(v);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindItemViewHolder(SectioningAdapter.ItemViewHolder viewHolder, int sectionIndex, int itemIndex, int itemType) {
Section s = sections.get(sectionIndex);
ItemViewHolder ivh = (ItemViewHolder) viewHolder;
Person person = s.people.get(itemIndex);
ivh.personNameTextView.setText(capitalize(person.name.last) + ", " + capitalize(person.name.first));
}
#SuppressLint("SetTextI18n")
#Override
public void onBindHeaderViewHolder(SectioningAdapter.HeaderViewHolder viewHolder, int sectionIndex, int headerType) {
Section s = sections.get(sectionIndex);
HeaderViewHolder hvh = (HeaderViewHolder) viewHolder;
if (USE_DEBUG_APPEARANCE) {
hvh.itemView.setBackgroundColor(0x55ffffff);
hvh.titleTextView.setText(pad(sectionIndex * 2) + s.alpha);
} else {
hvh.titleTextView.setText(s.alpha);
}
}
private String capitalize(String s) {
if (s != null && s.length() > 0) {
return s.substring(0,1).toUpperCase(locale) + s.substring(1);
}
return "";
}
private String pad(int spaces) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < spaces; i++) {
b.append(' ');
}
return b.toString();
}
}
You can use comparable interface in your Transaction class and compare with particular field you want to sort

Using two different listview row types

I am trying to make a listview that contains soccer(football) teams fixtures but I have failed to alternate between the title(contains the date) and the matches under that date
This is mycode
public class FixturesCursorAdapter extends CursorAdapter {
private static final String TAG = "CURSORLOADER";
private final int VIEW_TYPE_TITLE = 0;
private final int VIEW_TYPE_BODY = 1;
private final int VIEW_TYPE_COUNT = 2;
private String itemname;
private int n = 0;
private ImageView imageView;
public static class ViewHolder {
public final TextView homeTeam;
public final TextView awayTeam;
public final TextView score;
public final TextView date;
public final ImageView homeImage;
public final ImageView awayImage;
public ViewHolder(View view) {
homeTeam = (TextView) view.findViewById(R.id.homeTeam);
awayTeam = (TextView) view.findViewById(R.id.awayTeam);
score = (TextView) view.findViewById(R.id.score);
date = (TextView) view.findViewById(R.id.date);
homeImage = (ImageView) view.findViewById(R.id.homeTeamImage);
awayImage = (ImageView) view.findViewById(R.id.awayImageTeam);
}
}
public FixturesCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getItemViewType(int position) {
return (position == 0)? VIEW_TYPE_TITLE : VIEW_TYPE_BODY;
}
#Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
if (viewType == VIEW_TYPE_TITLE){
layoutId = R.layout.fixtures_row_title;
}
else if (viewType == VIEW_TYPE_BODY){
layoutId = R.layout.fixtures_table_row;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor){
String homeTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_HOME_TEAM_NAME));
String awayTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_AWAY_TEAM_NAME));
String goalsHomeTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_GOALS_HOME_TEAM));
String goalsAwayTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_GOALS_AWAY_TEAM));
// String date = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_DATE));
Log.d("CURSOR_bindview", homeTeam);
Log.d("CURSOR_bindview", awayTeam);
ViewHolder viewHolder = (ViewHolder) view.getTag();
try {
viewHolder.homeTeam.setText(homeTeam);
viewHolder.awayTeam.setText(awayTeam);
viewHolder.score.setText(goalsHomeTeam + " - " + goalsAwayTeam);
// viewHolder.date.setText(Utility.timeTruncate(date));
Log.d("PicassoLoader", "initiating" + n);
for (n = 0; n < 2; n++) {
Log.d("PicassoLoader", "started" + n);
if (n == 0) {
itemname = homeTeam;
imageView = viewHolder.homeImage;
} else {
itemname = awayTeam;
imageView = viewHolder.awayImage;
}
if (imageView != null && itemname != null) {
Utility.picassoLoader(context, 0, imageView,itemname);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The title appears only at the top. So how can I manually switch between the title(VIEW_TYPE_TITLE) and body(VIEW_TYPE_BODY)
You shouldn't be using newView() to specify the view for each item. Use getView() instead.
See the answer to this question for details on what getView() and newView() and when to use each.

android ListView adapter with three different xml items

I am trying to create a listview with three different item types I have a code that works with two XML files
Here is the adapter code:
private class MyCustomAdapter extends ArrayAdapter<String> {
String hello;
private String place;
int image;
private String temp;
private String humidity;
private String windspeed;
private String condition;
private int imageTop;
private String time;
private static final int TYPE_WEATHER = 0;
private static final int TYPE_TIME = 1;
private static final int TYPE_TOP = 2;
private static final int TYPE_MAX_COUNT = 3 + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context, int resource) {
super(context, resource);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addWeather(final String place,final int image , final String temp,final String humidity,final String windspeed,final String condition) {
mData.add(place);
this.place = place;
this.image = image;
this.temp = temp;
this.humidity = humidity;
this.windspeed = windspeed;
this.condition = condition;
notifyDataSetChanged();
}
public void addFavapp(final String helloworld){
mData.add(place);
this.hello = helloworld;
notifyDataSetChanged();
}
public void addItem(final String item) {
this.time = item;
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_WEATHER : TYPE_TIME;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_WEATHER:
convertView = mInflater.inflate(R.layout.weather_item, null);
//Handling xml file weather_item
break;
case TYPE_TIME:
convertView = mInflater.inflate(R.layout.time_card_item, null);
holder.textView = (TextView)convertView.findViewById(R.id.two);
holder.textView.setText(time);
break;
case TYPE_TOP:
convertView = mInflater.inflate(R.layout.top_card_item, null);
//Handling xml file top_card_item
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
public ImageView image;
public TextView txtTemp;
public ImageView imageView;
public TextView txthumidity;
public TextView txtWind;
public TextView txtCond;
}
I tried creating a method called "addFavapp" to add my third XML file but I couldn't get it to work.
Help please.
Got it fixed by replacing
return mSeparatorsSet.contains(position) ? TYPE_WEATHER : TYPE_TIME;
Inside the getItemViewType
To
return position;

Categories

Resources