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;
}
}
}
Related
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
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().getDrawable(R.drawable.ic_launcher));
after
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
It will work
I have a problem with the list. My list consists of two rows. The first is simply information about the object. When I click on the first item is presented a second row. It has a timer, everything works as expected, but the re-acquired by the time starts ticking faster. I understand that it is necessary to clean the list or am I just doing something wrong. Help me please.
This is my code:
public class MainActivity extends Activity {
ArrayList<Childrens> arrayList = new ArrayList<Childrens>();
ChilndrensAdapter adapter;
ListView listView;
private static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
final Childrens ls = new Childrens();
arrayList = ls.getListView();
adapter = new ChilndrensAdapter(getApplicationContext(), arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (arrayList.get(position).status == false) {
Log.d("True", " True");
adapter.setSelecterIndex(position);
adapter.toggleSelected(new Integer(position));
adapter.startUpdateTimer(position);
adapter.notifyDataSetChanged();
} else if (arrayList.get(position).status == true) {
Log.d("False", " False");
adapter.setSelecterIndex(position);
adapter.toggleSelected(new Integer(position));
adapter.stopUpdateTimer(position);
adapter.notifyDataSetChanged();
}
}
});
}
public static Context getContext() {
return context;
}
}
Adapter:
public class ChilndrensAdapter extends BaseAdapter {
ArrayList<Childrens> arrayList;
Context context;
private LayoutInflater cInflater;
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
private ArrayList<ViewHolder> lstHolders;
private static final int END = 0;
private static final int START = 1;
Timer tmr = new Timer();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
//Log.d("Runnable","Runnable");
synchronized (lstHolders) {
long currentTime = 0L;
//long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining(currentTime);
}
}
}
};
public ChilndrensAdapter(Context context, ArrayList<Childrens> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.cInflater = LayoutInflater.from(context.getApplicationContext());
lstHolders = new ArrayList<>();
// startUpdateTimer();
}
public void startUpdateTimer(final int positon) {
arrayList.get(positon).status = true;
tmr.schedule(new TimerTask() {
#Override
public void run() {
//Log.d("tmr","tmr");
mHandler.post(updateRemainingTimeRunnable);
// arrayList.get(positon).time = arrayList.get(positon).time + 1;
}
}, 1000, 1000);
for (int i = 0; i < lstHolders.size(); i++) {
//Log.d("Holders: ","H: "+ i+" " + lstHolders.get(i) +" Size: " + lstHolders.size() + " Time: "+arrayList.get(positon).time);
}
}
public void stopUpdateTimer(int position) {
arrayList.get(position).time = 0;
arrayList.get(position).status = false;
// Log.d("Timer Run:", "Time is:" + lstHolders.size());
}
#Override
public int getCount() {
if (arrayList == null) {
return 0;
}
return arrayList.size();
}
public void setSelecterIndex(int ind) {
notifyDataSetChanged();
}
public void toggleSelected(Integer position) {
if (selectedIds.contains(position)) {
selectedIds.remove(position);
} else {
selectedIds.add(position);
}
}
#Override
public int getItemViewType(int position) {
if (selectedIds.contains(position)) {
return 1;
} else
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Childrens getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Childrens item = (Childrens) getItem(position);
int type = getItemViewType(position);
if (convertView == null) {
switch (type) {
case END:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_normal, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.info = (TextView) convertView.findViewById(R.id.name_control);
convertView.setTag(holder);
break;
case START:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_start, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name_start);
holder.button = (ImageView) convertView.findViewById(R.id.dialog_button);
holder.holderTimer = (TextView) convertView.findViewById(R.id.answerTime);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
break;
}
} else {
holder = (ViewHolder) convertView.getTag();
}
switch (type) {
case END:
holder.name.setText(item.name);
holder.info.setText("Time");
break;
case START:
holder.setData(getItem(position));
holder.name.setText(item.name);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.getContext());
dialog.setTitle("Position " + position);
dialog.setContentView(R.layout.dialog);
dialog.show();
}
});
break;
}
return convertView;
}
public class ViewHolder {
private TextView name;
private TextView info;
public TextView holderTimer;
public ImageView button;
Childrens mChildrens;
public void setData(Childrens item) {
mChildrens = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
int sec = (mChildrens.time) % 60;
int min = (mChildrens.time / 60) % 60;
holderTimer.setText(String.format("%02d", min) + ":" + String.format("%02d", sec));
// holderTimer.setText("Time: " + min +":"+ sec);
}
}
}
Object:
public class Childrens {
public String name;
public int id;
public long answerTime = 0;
public boolean status;
public int time;
final static Childrens CHILDRENS_STATE = new Childrens();
Childrens(String n, int id, long answerTime) {
this.name = n;
this.id = id;
this.answerTime = answerTime;
}
Childrens() {
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public static Childrens getInstance() {
return CHILDRENS_STATE;
}
public ArrayList<Childrens> getListView() {
ArrayList<Childrens> arrayList = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
Childrens c = new Childrens();
c.status = false;
c.name = "Child: " + i;
c.time = 0;
arrayList.add(c);
//arrayList.add(new Childrens("Tata"+ i, i, answerTime));
}
return arrayList;
}
}
Sorry there was mistake in adapter
public class ChilndrensAdapter extends BaseAdapter {
ArrayList<Childrens> arrayList;
Context context;
private LayoutInflater cInflater;
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
private ArrayList<ViewHolder> lstHolders;
private static final int END = 0;
private static final int START = 1;
Timer tmr = new Timer();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
public ChilndrensAdapter(Context context, ArrayList<Childrens> arrayList){
this.context = context;
this.arrayList = arrayList;
this.cInflater = LayoutInflater.from(context.getApplicationContext());
lstHolders = new ArrayList<>();
}
public void startUpdateTimer(final int positon) {
arrayList.get(positon).status = true;
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
arrayList.get(positon).time = arrayList.get(positon).time + 1;
}
}, 1000, 1000);
}
public void stopUpdateTimer(int position) {
arrayList.get(position).time = 0;
arrayList.get(position).status = false;
}
#Override
public int getCount() {
if(arrayList == null){
return 0;
}
return arrayList.size();
}
public void setSelecterIndex(int ind){
notifyDataSetChanged();
}
public void toggleSelected(Integer position){
if (selectedIds.contains(position)){
selectedIds.remove(position);
}else {
selectedIds.add(position);
}
}
#Override
public int getItemViewType(int position) {
if (selectedIds.contains(position)){
return 1;
}else
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Childrens getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Childrens item = (Childrens) getItem(position);
int type = getItemViewType(position);
if(convertView == null){
switch (type){
case END:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_normal, parent,false);
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.info = (TextView)convertView.findViewById(R.id.name_control);
convertView.setTag(holder);
break;
case START:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_start, parent, false);
holder.name = (TextView)convertView.findViewById(R.id.name_start);
holder.button = (ImageView)convertView.findViewById(R.id.dialog_button);
holder.holderTimer = (TextView)convertView.findViewById(R.id.answerTime);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
break;
}
}else {
holder = (ViewHolder) convertView.getTag();
}
switch (type){
case END:
holder.name.setText(item.name);
holder.info.setText("Time");
break;
case START:
holder.setData(getItem(position));
holder.name.setText(item.name);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.getContext());
dialog.setTitle("Position " + position);
dialog.setContentView(R.layout.dialog);
dialog.show();
}
});
break;
}
return convertView;
}
public class ViewHolder{
private TextView name;
private TextView info;
public TextView holderTimer;
public ImageView button;
Childrens mChildrens;
public void setData(Childrens item) {
mChildrens = item;
updateTimeRemaining();
}
public void updateTimeRemaining(long currentTime) {
int sec = (mChildrens.time)%60;
int min = (mChildrens.time/60)%60;
holderTimer.setText(String.format("%02d", min) + ":" + String.format("%02d", sec));
}
}
}
I solved the problem and I want to share with you the ready code.
When creating a new timer I dobovlyaet it to your array of, and with the second click on an element and find this timer is reset to zero it. Although at this point I'm going to send data to the server to zero. Generally it works, check!
public class ChilndrensAdapter extends BaseAdapter {
ArrayList<Childrens> arrayList;
Context context;
private LayoutInflater cInflater;
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
private ArrayList<ViewHolder> lstHolders;
private static final int END = 0;
private static final int START = 1;
Timer tmr;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
public ChilndrensAdapter(Context context, ArrayList<Childrens> arrayList){
this.context = context;
this.arrayList = arrayList;
this.cInflater = LayoutInflater.from(context.getApplicationContext());
lstHolders = new ArrayList<>();
}
public void startUpdateTimer(final int positon) {
arrayList.get(positon).status = true;
tmr = new Timer();
arrayList.get(positon).timer = tmr;
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
arrayList.get(positon).time = arrayList.get(positon).time + 1;
}
}, 1000, 1000);
}
public void stopUpdateTimer(int position) {
arrayList.get(position).timer.cancel();
arrayList.get(position).timer = null;
arrayList.get(position).time = 0;
arrayList.get(position).status = false;
}
#Override
public int getCount() {
if(arrayList == null){
return 0;
}
return arrayList.size();
}
public void setSelecterIndex(int ind){
notifyDataSetChanged();
}
public void toggleSelected(Integer position){
if (selectedIds.contains(position)){
selectedIds.remove(position);
}else {
selectedIds.add(position);
}
}
#Override
public int getItemViewType(int position) {
if (selectedIds.contains(position)){
return 1;
}else
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public Childrens getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Childrens item = (Childrens) getItem(position);
int type = getItemViewType(position);
if(convertView == null){
switch (type){
case END:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_normal, parent,false);
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.info = (TextView)convertView.findViewById(R.id.name_control);
convertView.setTag(holder);
break;
case START:
holder = new ViewHolder();
convertView = cInflater.inflate(R.layout.listview_row_start, parent, false);
holder.name = (TextView)convertView.findViewById(R.id.name_start);
holder.button = (ImageView)convertView.findViewById(R.id.dialog_button);
holder.holderTimer = (TextView)convertView.findViewById(R.id.answerTime);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
break;
}
}else {
holder = (ViewHolder) convertView.getTag();
}
switch (type){
case END:
holder.name.setText(item.name);
holder.info.setText("Time");
break;
case START:
holder.setData(getItem(position));
holder.name.setText(item.name);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.getContext());
dialog.setTitle("Position " + position);
dialog.setContentView(R.layout.dialog);
dialog.show();
}
});
break;
}
return convertView;
}
public class ViewHolder{
private TextView name;
private TextView info;
public TextView holderTimer;
public ImageView button;
Childrens mChildrens;
public void setData(Childrens item) {
mChildrens = item;
updateTimeRemaining();
}
public void updateTimeRemaining() {
int sec = (mChildrens.time)%60;
int min = (mChildrens.time/60)%60;
holderTimer.setText(String.format("%02d", min) + ":" + String.format("%02d", sec));
}
}
}
I have a ListView which is having 2 types of headers & within this I want to implement another type of header known as StickyListHeader
Well, Implementing 2 types of header was a complex task for me & now within that implementing StickyListHeader is not an easy task. Let for every 5th view I have to add a StickyListHeader.
This is the code :
public class ContentsFragment extends ListFragment implements OnTouchListener,AbsListView.OnScrollListener {
private MyCustomAdapter mAdapter;
Activity temp = getActivity();
String []s = new String[500];
ArrayList<GS> q = new ArrayList<GS>();
ListView lv;
int count=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter db = DBAdapter.getDBAdapter(getActivity());
if (!db.checkDatabase())
db.createDatabase(getActivity());
db.openDatabase();
q = db.getData();
mAdapter = new MyCustomAdapter(getActivity());
mAdapter.addSeparatorItem(new ContentWrapper(q.get(0).getA_name(),null,null));
mAdapter.addItem(new ContentWrapper(q.get(0).getAS_name(), q.get(0).getDesc_art(),null));
for (int i = 1; i <= 14; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(new ContentWrapper(q.get(i).getA_name(), null,null));
}
if(!(q.get(i).getExtra()==null))
mAdapter.addGraySeparatorItem(new ContentWrapper(q.get(i).getExtra(),null,null));
mAdapter.addItem(new ContentWrapper(q.get(i).getAS_name(), q.get(i).getDesc_art(),null));
}
for (int i = 15; i < 36; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(new ContentWrapper(q.get(i).getA_name(), null,null));
}
if(!(q.get(i).getExtra()==null))
mAdapter.addGraySeparatorItem(new ContentWrapper(q.get(i).getExtra(),null,null));
mAdapter.addItem(new ContentWrapper(q.get(i).getAS_name(), q.get(i).getDesc_art(),null));
}
//Adapter Class
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_GRAY_SEPARATOR = 2;
private static final int TYPE_MAX_COUNT = TYPE_GRAY_SEPARATOR + 1;
private TreeSet<Integer> mGraySeparatorsSet = new TreeSet<Integer>();
private ArrayList<ContentWrapper> mData = new ArrayList<ContentWrapper>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context)
{
mInflater = LayoutInflater.from(context);
}
public void addItem(ContentWrapper value) {
mData.add(value);
notifyDataSetChanged();
}
public void addSeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addGraySeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mGraySeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public ContentWrapper getItem(int position) {
return mData.get(position);
}
#Override
public int getItemViewType(int position) {
int viewType = TYPE_ITEM;
if(mSeparatorsSet.contains(position))
viewType = TYPE_SEPARATOR;
else if(mGraySeparatorsSet.contains(position)) {
viewType = TYPE_GRAY_SEPARATOR;
}
return viewType;
// return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public long getItemId(int position) {
Log.v("getItemId Position", ""+position);
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.white, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.black, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
case 2:
convertView = mInflater.inflate(R.layout.gray, null);
holder.textView = (TextView)convertView.findViewById(R.id.textViewGray);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
} holder.textView.setText(mData.get(position).getItem());
getListView().setFastScrollEnabled(true);
if (type == TYPE_ITEM) {
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(R.drawable.ic_launcher);
final String title = mData.get(position).getItem();
builder.setTitle(title);
builder.setMessage(mData.get(position).getItemDescription());
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
AlertDialog alertDialog = (AlertDialog) dialog;
ViewGroup viewGroup = (ViewGroup) alertDialog.getWindow()
.getDecorView();
TextView textView = findTextViewWithTitle(viewGroup, title);
if (textView != null) {
textView.setEllipsize(null);
textView.setMaxHeight((int) (100 * alertDialog.getContext().getResources().getDisplayMetrics().density));
textView.setMovementMethod(new ScrollingMovementMethod());
}
}
});
alertDialog.show();
}
private TextView findTextViewWithTitle(ViewGroup viewGroup, String title) {
for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof TextView) {
TextView textView = (TextView) child;
if (textView.getText().equals(title)) {
return textView;
}
} else if (child instanceof ViewGroup) {
ViewGroup vGroup = (ViewGroup) child;
return findTextViewWithTitle(vGroup, title);
}
}
return null;
}
});
}else if(type == 1) {
holder.textView.setOnClickListener(null);
}
else
{
holder.textView.setOnClickListener(null);
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
public TextView header;
int previousTop = 0;
}
public boolean onTouch(View v, MotionEvent event) {
return false;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//the listview has only few children (of course according to the height of each child) who are visible
for(int i=0; i < getListView().getChildCount(); i++){
View child = getListView().getChildAt(i);
ViewHolder holder = (ViewHolder) child.getTag();
//if the view is the first item at the top we will do some processing
if(i == 0){
boolean isAtBottom = child.getHeight() <= holder.header.getBottom();
int offset = holder.previousTop - child.getTop();
if(!(isAtBottom && offset > 0)){
holder.previousTop = child.getTop();
holder.header.offsetTopAndBottom(offset);
holder.header.invalidate();
}
} //if the view is not the first item it "may" need some correction because of view re-use
else if (holder.header.getTop() != 0) {
int offset = -1 * holder.header.getTop();
holder.header.offsetTopAndBottom(offset);
holder.previousTop = 0;
holder.header.invalidate();
}
}
}
}
As you can see for StickyListHeader I implemented onScroll() method .
Now I think in the modification have to be done in class MyCustomAdapter constructor & in also getView() method beacuse I am follwing this example & it states that we have to deal with constructor,getView() & onScroll().
Can anyone tell me what should I modify to accomplish my task.
Thank You
For Header Listview you should use HeaderListView OR PinnedHeaderListView Library.very easy to use.
The below code is running the custom listview implemented in a seperate project.
public class MainActivity extends ListActivity implements OnTouchListener{
private MyCustomAdapter mAdapter;
Activity temp = this;
String []s = new String[500];
ArrayList<GS> q = new ArrayList<GS>();
ListView lv;
int count=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
if (!db.checkDatabase())
{
db.createDatabase(getApplicationContext());
}
db.openDatabase();
q = db.getData();
mAdapter = new MyCustomAdapter();
mAdapter.addSeparatorItem(new ContentWrapper(q.get(0).getA_name(),null));
mAdapter.addItem(new ContentWrapper(q.get(0).getAS_name(), q.get(0).getDesc_art()));
for (int i = 1; i < 460; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(new ContentWrapper(q.get(i).getA_name(), null));
}
mAdapter.addItem(new ContentWrapper(q.get(i).getAS_name(), q.get(i).getDesc_art()));
}
setListAdapter(mAdapter);
}
//Adapter Class
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<ContentWrapper> mData = new ArrayList<ContentWrapper>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(ContentWrapper value) {
mData.add(value);
notifyDataSetChanged();
}
public void addSeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public ContentWrapper getItem(int position) {
return mData.get(position);
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public long getItemId(int position) {
Log.v("getItemId Position", ""+position);
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.activity_main1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.activity_main2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
count++;
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
} holder.textView.setText(mData.get(position).getItem());
if (type == TYPE_ITEM) {
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder x = new AlertDialog.Builder(temp);
Log.v("position",""+position);
x.setIcon(R.drawable.ic_launcher)
// .setTitle(q.get(position-count).getAS_name())
.setTitle(mData.get(position).getItem())
// .setMessage(q.get(position-count).getDesc_art())
.setMessage(mData.get(position).getItemDescription())
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg,
int arg1) {
}
});
AlertDialog a = x.create();
a.show();
}
});
} else {
holder.textView.setOnClickListener(null);
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
Now I want it to be running the same in my App with Fragment.
I just know that using fragment = new ContentsFragment(); initiates it in fragment.
should it be extending ListFragment with a default constructor & an onCreateView(...) which I have inflated the another activities
I am new to fragments & i don't know what things should be changed in the code.
Please help !
EDIT:
I am showing my implemented code of what i have tried & i am getting 4 errors which are have specified in the code:
public class ContentsFragment extends Fragment implements OnTouchListener{
private MyCustomAdapter mAdapter;
Activity temp = this;// error: Type mismatch: cannot convert from ContentsFragment to Activity
String []s = new String[500];
ArrayList<GS> q = new ArrayList<GS>();
ListView lv;
int count=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());//error :The method getApplicationContext() is undefined for the type ContentsFragment
if (!db.checkDatabase())
{
db.createDatabase(getApplicationContext());//error : The method getApplicationContext() is undefined for the type ContentsFragment
}
db.openDatabase();
q = db.getData();
mAdapter = new MyCustomAdapter();
mAdapter.addSeparatorItem(new ContentWrapper(q.get(0).getA_name(),null));
mAdapter.addItem(new ContentWrapper(q.get(0).getAS_name(), q.get(0).getDesc_art()));
for (int i = 1; i < 460; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(new ContentWrapper(q.get(i).getA_name(), null));
}
mAdapter.addItem(new ContentWrapper(q.get(i).getAS_name(), q.get(i).getDesc_art()));
}
setListAdapter(mAdapter); //error : The method getApplicationContext() is undefined for the type ContentsFragment
}
//Adapter Class
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<ContentWrapper> mData = new ArrayList<ContentWrapper>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(ContentWrapper value) {
mData.add(value);
notifyDataSetChanged();
}
public void addSeparatorItem(ContentWrapper value) {
mData.add(value);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public ContentWrapper getItem(int position) {
return mData.get(position);
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public long getItemId(int position) {
Log.v("getItemId Position", ""+position);
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.activity_main1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.activity_main2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
count++;
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
} holder.textView.setText(mData.get(position).getItem());
if (type == TYPE_ITEM) {
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder x = new AlertDialog.Builder(temp);
Log.v("position",""+position);
x.setIcon(R.drawable.ic_launcher)
// .setTitle(q.get(position-count).getAS_name())
.setTitle(mData.get(position).getItem())
// .setMessage(q.get(position-count).getDesc_art())
.setMessage(mData.get(position).getItemDescription())
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg,
int arg1) {
}
});
AlertDialog a = x.create();
a.show();
}
});
} else {
holder.textView.setOnClickListener(null);
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
setListAdapter is a method of ListFragment. So you need to extend ListFragment to use the same.
Change this
mAdapter = new MyCustomAdapter();
to
mAdapter = new MyCustomAdapter(getActivity());
And Then
public MyCustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}