Implement StickyListHeader in ListView with headers - android

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.

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

Android custom listview View with timer

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

ListView Header implementation

I have an Adapter class that implements ListView with headers.
//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 static final int TYPE_GRAY_SEPARATOR = 2;
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 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.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;
}
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(getActivity());
x.setIcon(R.drawable.ic_launcher)
.setTitle(mData.get(position).getItem())
.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();
}
return null;
}
});
} else {
holder.textView.setOnClickListener(null);
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
In this I truly understand the implementation of getView method (ViewHolder,convertView,etc).
The above code runs smoothy but I do not understand that why we are using the methods
addItem
addSeparatorItem
getItemViewType
getViewTypeCount
getCount
getItemId
Can Anyone explain me the scenario clearly !
Thanks in advance..
These all are the call back methods. You can have the clear definition of these methods in below mentioned link.
http://developer.android.com/reference/android/widget/BaseAdapter.html
Let me give you an example of getItem()
Whenever new listview row is created, adapte willl get item details from this call back method.
Similarly whenever list is created, getCount() is called.
Suppose you have 12 items in listview. But you pass 10 in getCount(). it will show only ten items in list view.

Using ListActivity in Fragment

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

Slider menu View issue

I have implemented a ListView with headers from sqlite in a separate project which is like this:
When I implemented onClick() in a position of Slider Menu, It is displayed in Slider Menu rather than in the background View
onCreate() code snippet
if(position == 3)
{
mAdapter = new MyCustomAdapter();
mAdapter.addSeparatorItem(q.get(0).getA_name());
mAdapter.addItem(q.get(0).getAS_name());
for (int i = 1; i < 460; i++) {
if (!(q.get(i).getA_name().trim().equals(q.get(i-1).getA_name().trim()))) {
mAdapter.addSeparatorItem(q.get(i).getA_name());
c++;
}
mAdapter.addItem(q.get(i).getAS_name());
}
setListAdapter(mAdapter);
toggleMenu(arg1);
}
Adapter class
//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<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#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 String getItem(int position) {
return mData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final 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_ITEM:
convertView = mInflater.inflate(R.layout.activity_main1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder nointernetconnection = new AlertDialog.Builder(
temp);
nointernetconnection
.setIcon(R.drawable.ic_launcher)
.setTitle(q.get(position-1).getAS_name())
.setMessage(q.get(position-1).getDesc_art())
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg,
int arg1) {
}
});
AlertDialog a = nointernetconnection.create();
a.show();
}
});
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.activity_main2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
So, MyCustomAdapter class is dispalying the list in slider menu. But this list should not be displayed in slider menu rather it should be displayed behind slider menu. I hope the problem is clear. Please tell my mistake.
The setlistadapter method you are calling is being called for the slider rather than your list view on the activity/fragment in the background.
do a ListView list = (ListView) getactivity().findViewById(R.id.yourListViewName) or something like this, and then set the list adapter.

Categories

Resources