Android actionbar: Custom fade animation on tab icon and title - java

I'm trying to make a custom animation that works pretty much the same way the tumblr android app works using the standard actionbar. (Not fading of the content of the tabs) I'm pretty close to getting it working but I have troubles fixing the last part. Maybe someone here can help me in the right direction to get this working.
EDIT: Image to show what I mean: IMAGE
What I have.
In onCreate I add some custom views for the tabs:
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
final CustomPageTransformer cpt = new CustomPageTransformer();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
cpt.currentItem = position;
}
});
mViewPager.setPageTransformer(true, cpt);
CustomTabView tabNews = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(0).toString(), mSectionsPagerAdapter.getIcon(0));
CustomTabView tabEvents = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(1).toString(), mSectionsPagerAdapter.getIcon(1));
CustomTabView tabContacts = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(2).toString(), mSectionsPagerAdapter.getIcon(2));
CustomTabView tabClub = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(3).toString(), mSectionsPagerAdapter.getIcon(3));
actionBar.addTab(actionBar.newTab().setCustomView(tabNews).setTabListener(this).setTag(0));
actionBar.addTab(actionBar.newTab().setCustomView(tabEvents).setTabListener(this).setTag(1));
actionBar.addTab(actionBar.newTab().setCustomView(tabContacts).setTabListener(this).setTag(2));
actionBar.addTab(actionBar.newTab().setCustomView(tabClub).setTabListener(this).setTag(3));
The CustomTabView looks like this, where I've added two custom view so I can easily set the alpha of the views:
public class CustomTabView extends RelativeLayout {
AlphaTextView text1;
AlphaImageView icon1;
int alpha;
public CustomTabView(Context context, String text, Drawable icon) {
super(context);
init(context, text, icon);
}
public CustomTabView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, null, null);
}
public CustomTabView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, null, null);
}
private void init(Context context, String text, Drawable icon) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.tab_view, this, true);
text1 = (AlphaTextView) findViewById(R.id.title);
text1.setTypeface(Font.rMedium(context));
text1.setText(text);
icon1 = (AlphaImageView) findViewById(R.id.icon);
icon1.setImageDrawable(icon);
setTheAlpha(128);
}
public void setTheAlpha(int aleph) {
this.alpha = aleph;
if (alpha < 128) alpha = 128;
if (alpha > 255) alpha = 255;
text1.onSetAlpha(alpha);
icon1.onSetAlpha(alpha);
}
public int getTheAlpha() {
return alpha;
}
}
Then there is the problem, the CustomPageTransformer:
public class CustomPageTransformer implements ViewPager.PageTransformer {
public int currentItem = 0;
View currentView = null;
public CustomTabView tabNews = null;
public CustomTabView tabEvents = null;
public CustomTabView tabContacts = null;
public CustomTabView tabClub = null;
#Override
public void transformPage(View view, float position) {
if (position != 0.0 && position != 1.0 && position != 2.0 && position != -1.0) {
if (currentView == null) {
currentView = view;
Log.e("First number", String.valueOf(position));
}
} else if (position == 0.0 || position == 1.0 || position == 2.0 || position == -1.0 || position == -2.0) currentView = null;
if (view == currentView) {
int alphaCurrent = (int) (255 - (128*Math.abs(position)));
if (alphaCurrent > 255) alphaCurrent = 255;
else if (alphaCurrent < 128) alphaCurrent = 128;
int alphaNext = (int) (128 + (128*Math.abs(position)));
if (alphaNext > 255) alphaNext = 255;
else if (alphaNext < 128) alphaNext = 128;
if (tabNews != null && tabEvents != null && tabContacts != null && tabClub != null) {
switch(currentItem) {
case 0:
if (position <= -1) {
tabNews.setTheAlpha(128);
tabEvents.setTheAlpha(255);
} else if (position <= 0) {
tabNews.setTheAlpha(alphaCurrent);
tabEvents.setTheAlpha(alphaNext);
}
break;
case 1:
if (position <= -1) {
tabEvents.setTheAlpha(128);
tabContacts.setTheAlpha(255);
} else if (position <= 0) {
tabEvents.setTheAlpha(alphaCurrent);
tabContacts.setTheAlpha(alphaNext);
} else if (position <= 1) {
tabEvents.setTheAlpha(alphaCurrent);
tabNews.setTheAlpha(alphaNext);
} else if (position > 1) {
tabEvents.setTheAlpha(128);
tabNews.setTheAlpha(255);
}
break;
case 2:
if (position <= -1) {
tabContacts.setTheAlpha(128);
tabClub.setTheAlpha(255);
} else if (position <= 0) {
tabContacts.setTheAlpha(alphaCurrent);
tabClub.setTheAlpha(alphaNext);
} else if (position <= 1) {
tabContacts.setTheAlpha(alphaCurrent);
tabEvents.setTheAlpha(alphaNext);
} else if (position > 1) {
tabEvents.setTheAlpha(255);
tabContacts.setTheAlpha(128);
}
break;
case 3:
if (position <= 1) {
tabClub.setTheAlpha(alphaCurrent);
tabContacts.setTheAlpha(alphaNext);
} else if (position > 1) {
tabClub.setTheAlpha(128);
tabContacts.setTheAlpha(255);
}
break;
}
}
}
}
}
The transformPage method gets (View & Position). The view is always the fragment you are going to and from in the viewpager, so every second time I have a positive value in position and then the next a negative value depending on which direction you are sliding.
First I thought I could use the view to determine which the current tab is and what direction I'm going in by taking whatever view comes first, but that seems to be random.
And since the position value jumps from negative to positive it generates a bit of a random fading result in the tabs.
Any ideas of how I can get this to work smoothly?

I found a better way of achieving this without using the page transformer. By using setOnPageChangeListener.
I've made an example app here: https://github.com/andreborud/FadingTabs
The code is pretty much just this:
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int alphaCurrent = (int) (255 - (128*Math.abs(positionOffset)));
int alphaNext = (int) (128 + (128*Math.abs(positionOffset)));
if (positionOffset != 0) {
switch(position) {
case 0:
tab0.setTheAlpha(alphaCurrent);
tab1.setTheAlpha(alphaNext);
break;
case 1:
tab1.setTheAlpha(alphaCurrent);
tab2.setTheAlpha(alphaNext);
break;
case 2:
tab2.setTheAlpha(alphaCurrent);
tab3.setTheAlpha(alphaNext);
break;
}
}
}
});

Related

Display list user with gridview android studio

I'm having trouble removing the "parent channel shortcut" even though I already have it hidden (view2.setvisiblity(view.GONE)). I'm using gridview android:numColumns="3".The list user display starts from the left side, If I want to remove it, how do I do that?
#Override
public int getCount() {
int count = currentusers.size() + subchannels.size() + stickychannels.size();
if ((curchannel != null) && (curchannel.nParentID > 0)) {
count++; // include parent channel shortcut
}
return count;
}
#Override
public Object getItem(int position) {
if (position < stickychannels.size()) {
return stickychannels.get(position);
}
// sticky channels are first so subtract these
position -= stickychannels.size();
if (position < currentusers.size()) {
return currentusers.get(position);
}
// users are first so subtract these
position -= currentusers.size();
if ((curchannel != null) && (curchannel.nParentID > 0)) {
if(position == 0) {
Channel parent = ttservice.getChannels().get(curchannel.nParentID);
if(parent != null)
return parent;
return new Channel();
}
position--; // subtract parent channel shortcut
}
return subchannels.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
if (position < stickychannels.size())
return INFO_VIEW_TYPE;
// sticky channels are first so subtract these
position -= stickychannels.size();
if (position < currentusers.size())
return USER_VIEW_TYPE;
// users are first so subtract these
position -= currentusers.size();
if ((curchannel != null) && (curchannel.nParentID > 0)) {
if (position == 0) {
return PARENT_CHANNEL_VIEW_TYPE;
}
position--; // subtract parent channel shortcut
}
return CHANNEL_VIEW_TYPE;
}
#Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Object item = getItem(position);
if(item instanceof Channel) {
final Channel channel = (Channel) item;
switch (getItemViewType(position)) {
case PARENT_CHANNEL_VIEW_TYPE :
// show parent channel shortcut
if (convertView == null ||
convertView.findViewById(R.id.parentname) == null)
convertView = inflater.inflate(R.layout.item_channel_back, parent, false);
convertView.setVisibility(view.GONE)
break;
case CHANNEL_VIEW_TYPE :
if (convertView == null ||
convertView.findViewById(R.id.channelname) == null)
convertView = inflater.inflate(R.layout.item_channel, parent, false);
ImageView chanicon = convertView.findViewById(R.id.channelicon);
TextView name = convertView.findViewById(R.id.channelname);
TextView topic = convertView.findViewById(R.id.chantopic);
Button join = convertView.findViewById(R.id.join_btn);
int icon_resource = R.drawable.channel_orange;
if(channel.bPassword) {
icon_resource = R.drawable.channel_pink;
chanicon.setContentDescription(getString(R.string.text_passwdprot));
chanicon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
else {
chanicon.setContentDescription(null);
chanicon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
}
chanicon.setImageResource(icon_resource);
if(channel.nParentID == 0) {
// show server name as channel name for root channel
ServerProperties srvprop = new ServerProperties();
ttclient.getServerProperties(srvprop);
name.setText(srvprop.szServerName);
}
else {
name.setText(channel.szName);
}
topic.setText(channel.szTopic);
OnClickListener listener = v -> {
if (v.getId() == R.id.join_btn) {
joinChannel(channel);
}
};
join.setOnClickListener(listener);
join.setAccessibilityDelegate(accessibilityAssistant);
join.setEnabled(channel.nChannelID != ttclient.getMyChannelID());
if (channel.nMaxUsers > 0) {
int population = Utils.getUsers(channel.nChannelID, ttservice.getUsers()).size();
((TextView)convertView.findViewById(R.id.population)).setText((population > 0) ? String.format("(%d)", population) : "");
}
break;
case INFO_VIEW_TYPE :
if (convertView == null ||
convertView.findViewById(R.id.titletext) == null)
convertView = inflater.inflate(R.layout.item_info, parent, false);
TextView title = convertView.findViewById(R.id.titletext);
TextView details = convertView.findViewById(R.id.infodetails);
title.setText(channel.szName);
details.setText(channel.szTopic);
break;
}
}
else if(item instanceof User) {
if (convertView == null ||
convertView.findViewById(R.id.nickname) == null)
convertView = inflater.inflate(R.layout.item_user, parent, false);
ImageView usericon = convertView.findViewById(R.id.usericon);
TextView nickname = convertView.findViewById(R.id.nickname);
TextView status = convertView.findViewById(R.id.status);
final User user = (User) item;
String name = Utils.getDisplayName(getBaseContext(), user);
nickname.setText(name);
status.setText(user.szStatusMsg);
boolean talking = (user.uUserState & UserState.USERSTATE_VOICE) != 0;
boolean female = (user.nStatusMode & TeamTalkConstants.STATUSMODE_FEMALE) != 0;
boolean away = (user.nStatusMode & TeamTalkConstants.STATUSMODE_AWAY) != 0;
int icon_resource;
if(user.nUserID == ttservice.getTTInstance().getMyUserID()) {
talking = ttservice.isVoiceTransmitting();
}
if(talking) {
if(female) {
icon_resource = R.drawable.woman_green;
nickname.setContentDescription(getString(R.string.user_state_now_speaking, name) + " 👩");
}
else {
icon_resource = R.drawable.man_green;
nickname.setContentDescription(getString(R.string.user_state_now_speaking, name) + " 👨");
}
}
else {
if(female) {
icon_resource = away? R.drawable.woman_orange : R.drawable.woman_blue;
nickname.setContentDescription(name + " 👩");
}
else {
icon_resource = away? R.drawable.man_orange : R.drawable.man_blue;
nickname.setContentDescription(name + " 👨");
}
}
status.setContentDescription(away ? getString(R.string.user_state_away) : null);
usericon.setImageResource(icon_resource);
usericon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
Button sndmsg = convertView.findViewById(R.id.msg_btn);
OnClickListener listener = v -> {
if (v.getId() == R.id.msg_btn) {
Intent intent = new Intent(MainActivity.this, TextMessageActivity.class);
startActivity(intent.putExtra(TextMessageActivity.EXTRA_USERID, user.nUserID));
}
};
sndmsg.setOnClickListener(listener);
sndmsg.setAccessibilityDelegate(accessibilityAssistant);
}
convertView.setAccessibilityDelegate(accessibilityAssistant);
return convertView;
}
The list user display starts from the left side

Snap HorizontalScrollView

I got the code below from here.
This code snaps the items of HorizontalScrollView. I tried a lot to implement this customView inside my layout but I am not able to figure out to how to attach my layout to it.
This example does add the views programmatically and calls them Features.
In XML I have done "my package name.view" but I cannot figure out how to call setFeatureItems so that my Views can be attached to it.
The snapping feature can be applied on RecyclerView easily by using SnapHelper but I haven't found anything for HorizontalScrollView.
public class HomeFeatureLayout extends HorizontalScrollView {
private static final int SWIPE_MIN_DISTANCE = 5;
private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private ArrayList mItems = null;
private GestureDetector mGestureDetector;
private int mActiveFeature = 0;
public HomeFeatureLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public HomeFeatureLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HomeFeatureLayout(Context context) {
super(context);
}
public void setFeatureItems(ArrayList items){
LinearLayout internalWrapper = new LinearLayout(getContext());
internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
addView(internalWrapper);
this.mItems = items;
for(int i = 0; i< items.size();i++){
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.homefeature,null);
//...
//Create the view for each screen in the scroll view
//...
internalWrapper.addView(featureLayout);
}
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//If the user swipes
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
int scrollX = getScrollX();
int featureWidth = v.getMeasuredWidth();
mActiveFeature = ((scrollX + (featureWidth/2))/featureWidth);
int scrollTo = mActiveFeature*featureWidth;
smoothScrollTo(scrollTo, 0);
return true;
}
else{
return false;
}
}
});
mGestureDetector = new GestureDetector(new MyGestureDetector());
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
//right to left
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
//left to right
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
} catch (Exception e) {
Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
}
return false;
}
}
}
in your recycleview adapter you will have reference to HomeFeatureLayout there you can call
homeFeatureLayout.setFeatureItems(items);
EDIT
public void setFeatureItems(ArrayList items){
for(int i = 0; i< items.size();i++){
// here you need to provide layout of individual items in your horizontal scrollview
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.anyLayout,null);
//...
//display information here
//...
TextView title = (TextView)featureLayout.findviewById(R.id.title);
title.setText("view title "+item.get(i).getTitle());
ImageView image = (ImageView)featureLayout.findviewById(R.id.icon);
image.setResourceId(R.drawable.icon);
internalWrapper.addView(featureLayout);
}
}

Android ListView Adapter getView() method calls more than one times [duplicate]

This question already has answers here:
custom listview adapter getView method being called multiple times, and in no coherent order
(12 answers)
Closed 6 years ago.
Java code
public class ContentListAdapter extends ArrayAdapter<Content> implements Filterable {
//private static final String TAG = ContentListAdapter.class.getCanonicalName();
private static final LogTracer LOG_TRACER = LogTracer.instance(ContentListAdapter.class);
private Context mContext;
private LayoutInflater mInflater;
private List<Content> mContents;
private List<Content> mContentsFiltered;
private int lastPosition = -1;
private boolean multiselectMode = false;
private Customer mCustomer = null;
private AdapterView.OnItemClickListener mOnItemClickListener;
private AdapterView.OnItemLongClickListener mOnItemLongClickListener;
PatientRatingDAO patientRatingDAO;
int completeVisiblePosition=0;
public int totalScrollCount= 0;
private boolean isFromHomeSearch;
private ListView mListView;
public View helpView;
public ContentListAdapter(Context context, List<Content> contents, ListView listView) {
super(context, R.layout.list_content, contents);
mContext = context;
mContents = contents;
mListView = listView;
mContentsFiltered = contents;
mInflater = LayoutInflater.from(mContext);
mCustomer = new CustomerDAO(context).getCurrentCustomer();
patientRatingDAO = new PatientRatingDAO(getContext());
}
private class ViewHolder {
View listContent;
ImageButton contentThumbnail, contentThumbnailNew,typeofarticle;
LinearLayout contentRightSec;
LinearLayout contentRightSecBottom;
TextView fileSize;
LinearLayout tagsView;
TextView contentPostTime;
TextView contentDescription;
TextView contentSource;
LinearLayout rateCountSec;
LinearLayout rateBarLayout;
TextView rateCount;
TextView likeCount;
TextView likeText;
ImageView likeImage,likeCountImage,rateCountImage,readtick;
RatingBar ratingBar;
RatingBar disabledRatingBar;
RelativeLayout patienteducation;
//int isLiked;
//int currentUserRateCount;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
// assign the view we are converting to a local variable
View v = convertView;
LOG_TRACER.d("parm getView " + position + " " + convertView);
// Calculating Scroll Count
if(getCompleteVisiblePosition() == 0){
if(v != null && mListView != null){
this.setCompleteVisiblePosition(calculateCompletelyVisibleListItems(v));
LOG_TRACER.d("parm completeVisiblePosition" + completeVisiblePosition);
}
}
if(getCompleteVisiblePosition() > 0){
if(position % getCompleteVisiblePosition() == 0){
totalScrollCount++;
LOG_TRACER.d("parm totalScrollCount" + totalScrollCount);
}
}
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//v = inflater.inflate(mLayout, null);
v = LayoutInflater.from(mContext).inflate(R.layout.list_content, parent, false);
ViewHolder holder = new ViewHolder();
holder.rateCount = (TextView) v.findViewById(R.id.rateCount);
holder.likeCount = (TextView) v.findViewById(R.id.likeCount);
holder.likeCountImage = (ImageView) v.findViewById(R.id.likeCountImage);
holder.rateCountImage = (ImageView) v.findViewById(R.id.rateCountImage);
holder.likeText = (TextView) v.findViewById(R.id.like_text);
holder.likeImage = (ImageView) v.findViewById(R.id.like_image);
holder.ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
holder.disabledRatingBar = (RatingBar) v.findViewById(R.id.disabled_rating_bar);
holder.typeofarticle = (ImageButton) v.findViewById(R.id.typeofarticle);
holder.patienteducation = (RelativeLayout) v.findViewById(R.id.patient_education);
v.setTag(holder);
}
final Content content = getItem(position);
final ViewHolder viewHolder = (ViewHolder) v.getTag();
if(viewHolder.listContent != null) {
if(content.getIs_Read() == Constants.INT_FLAG_YES) {
viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_grey);
viewHolder.readtick.setVisibility(View.VISIBLE);
} else {
viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_white);
viewHolder.readtick.setVisibility(View.GONE);
}
if(viewHolder.contentThumbnailNew != null){
Ion.with(viewHolder.contentThumbnailNew).fitXY().placeholder(R.drawable.imagethumbnail).fitXY().error(R.drawable.imagethumbnail).fitXY().load(
(!TextUtils.isEmpty(content.getDA_Thumbnail_Url()))?content.getDA_Thumbnail_Url().replaceAll(" ","%20") : content.getDA_Thumbnail_Url());
}
if(viewHolder.contentThumbnail != null) {
viewHolder.contentThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
if (multiselectMode) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
} else {
if (mOnItemLongClickListener != null)
mOnItemLongClickListener.onItemLongClick(null, v, position, position);
}
} else {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
}
}
});
viewHolder.contentThumbnailNew.setOnTouchListener(new TouchExtendedClickListener(mContext, new TouchExtendedClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view) {
if (mOnItemClickListener != null) mOnItemClickListener.onItemClick(null, convertView, position, position);
}
}));
viewHolder.contentThumbnailNew.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
if (multiselectMode) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
} else {
if (mOnItemLongClickListener != null)
mOnItemLongClickListener.onItemLongClick(null, v, position, position);
}
}
return true;
}
});
}
}
}
//To Set Ratings
if (viewHolder.rateCount != null) {
//Calculate rate count by (totalratigs/numberofusersrated)
if(content.getTotalRatings() == 0 || content.getTotalRatedCount()==0){
viewHolder.rateCount.setText("0");
}else if(content.getTotalRatedCount() != 0){
viewHolder.rateCount.setText(String.valueOf(Math.round(content.getTotalRatings()/content.getTotalRatedCount())));
}
}
//To Set Likes
if (viewHolder.likeCount != null) {
viewHolder.likeCount.setText(String.valueOf(content.getLikes()));
}
//if viewHolder.isLiked == 0 then user not yet liked else if viewHolder.isLiked == 1 the user liked
//viewHolder.isLiked = content.getIsLiked();
//viewHolder.currentUserRateCount = content.getCurrentUserRateCount();
//Add Like Listeners
if (viewHolder.likeText != null && viewHolder.likeImage != null) {
if(content.getIsLiked() == 0){
//Set liked image and text
viewHolder.likeText.setText("Like");
viewHolder.likeImage.setImageResource(R.drawable.ic_like_grey_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_grey_24dp);
}else{
//Set liked image and text
//viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
}
viewHolder.likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (content.getIsLiked() == 0) {
content.setIsLiked(1);
//To insert/update user likes to local database
PatientRating patientRating = patientRatingDAO.getByDACodeAndType(content.getDA_Code(),content.getContent_Type());
if(patientRating != null){
patientRating.setIsLiked(content.getIsLiked());
patientRatingDAO.update(patientRating);
}else{
patientRating = new PatientRating();
patientRating.setIsLiked(1);
patientRating.setContent_Type(content.getContent_Type());
patientRating.setDA_Code(content.getDA_Code());
patientRatingDAO.insert(patientRating);
}
//viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
//Increase like counts
int likes = 1 + Integer.parseInt(viewHolder.likeCount.getText().toString());
viewHolder.likeCount.setText(String.valueOf(likes));
viewHolder.rateBarLayout.setVisibility(View.VISIBLE);
Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.like_animation);
viewHolder.likeImage.startAnimation(animation);
//Toast.makeText(mContext, "Liked", Toast.LENGTH_SHORT).show();
return v;
}
#Override
public int getCount() {
return mContentsFiltered.size();
}
#Override
public Content getItem(int position) {
return mContentsFiltered.get(position);
}
public Filter getFilter(FilterOption filterOption) {
return getFilter();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase().trim();
FilterResults results = new FilterResults();
final List<Content> list = mContents;
int count = list.size() - 1;
List<Content> nlist = new ArrayList<Content>(list.size());
Content filterableContent;
for (int i = 0; i <= count; i++) {
filterableContent = list.get(i);
if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
} else if (!TextUtils.isEmpty(filterableContent.getTags())
&& filterableContent.getTags().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
}else if (!TextUtils.isEmpty(filterableContent.getCompany_Name())
&& filterableContent.getCompany_Name().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
}
}
/*List<Integer> companyIds = StaticVariableUtils.getFilterOption().getFilterCompanyIds();
for (int i = 0; i < count; i++) {
filterableContent = list.get(i);
if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
// if company ids are selected, check if
// the filtered content has slected company id
if(companyIds != null && companyIds.size() >= 1) {
if(companyIds.indexOf(filterableContent.getCompany_Id()) >= 0) {
nlist.add(filterableContent);
}
} else {
nlist.add(filterableContent);
}
}
}
List<Content> tmpList = new ArrayList<>(nlist.size());
if(nlist != null) {
// sort by datetime
Collections.sort(nlist, new Comparator<Content>() {
#Override
public int compare(Content lhs, Content rhs) {
if(StaticVariableUtils.getFilterOption().getSortingOrder() == R.string.sortingOrderLatest) {
return (lhs.getUploaded_Date().getTime()>rhs.getUploaded_Date().getTime()
? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
} else {
return (lhs.getUploaded_Date().getTime()<rhs.getUploaded_Date().getTime()
? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
}
}
});
}
FilterOption filterOption = StaticVariableUtils.getFilterOption();
if(filterOption.getShowByDate() == R.string.showByDateToday) {
nlist = filterByToday(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateLastWeek) {
nlist = filterByLastWeek(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateTwoWeeks) {
nlist = filterByTwoWeeks(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateThreeWeeks) {
nlist = filterByThreeWeeks(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateLastMonth) {
nlist = filterByLastMonth(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateOlder) {
nlist = filterByOlder(nlist);
}
if(filterOption.getShowByStatus() != R.string.showByStatusAll) {
nlist = getReadOrUnread(nlist, filterOption.getShowByStatus());
}*/
results.values = nlist;
results.count = nlist.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mContentsFiltered = (ArrayList<Content>) results.values;
notifyDataSetChanged();
}
};
}
my xml file
<ListView
android:id="#+id/lvContent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e2e2e2"
android:clipToPadding="false"
android:divider="#null"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:smoothScrollbar="true"
android:fitsSystemWindows="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:scrollbarStyle="insideOverlay">
</ListView>
getView method in Adapter of list view call multiple time at postion 0
So it is Taking a more time to Load this Activity.This codes are i am using....i don't know why getview() calls more than one time.and my working code is above.. how to Resolve this issue.
I Resolve this issuee...... Because i added list from three different methods and also set notifydatasetchange. so my get view called more than one time....

Listview with pull to refresh Scroll down to last item when adding header-view

I have created one pull to refresh listview now when I scroll or pull little bit then I have to add header view.
here my custom listview class
package com.app.refreshableList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.app.xxxxxx.R;
import com.google.android.gms.internal.el;
public class RefreshableListView extends ListView {
Boolean isScrool = false;
private View mHeaderContainer = null;
private View mHeaderView = null;
private ImageView mArrow = null;
private ProgressBar mProgress = null;
private TextView mText = null;
private float mY = 0;
private float mHistoricalY = 0;
private int mHistoricalTop = 0;
private int mInitialHeight = 0;
private boolean mFlag = false;
private boolean mArrowUp = false;
private boolean mIsRefreshing = false;
private int mHeaderHeight = 0;
private OnRefreshListener mListener = null;
private static final int REFRESH = 0;
private static final int NORMAL = 1;
private static final int HEADER_HEIGHT_DP = 62;
private static final String TAG = RefreshableListView.class.getSimpleName();
private ListViewObserver mObserver;
private View mTrackedChild;
private int mTrackedChildPrevPosition;
private int mTrackedChildPrevTop;
OnTouchListener touch;
View vHeader;
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mTrackedChild == null) {
if (getChildCount() > 0) {
mTrackedChild = getChildInTheMiddle();
mTrackedChildPrevTop = mTrackedChild.getTop();
mTrackedChildPrevPosition = getPositionForView(mTrackedChild);
}
} else {
boolean childIsSafeToTrack = mTrackedChild.getParent() == this
&& getPositionForView(mTrackedChild) == mTrackedChildPrevPosition;
if (childIsSafeToTrack) {
int top = mTrackedChild.getTop();
if (mObserver != null) {
float deltaY = top - mTrackedChildPrevTop;
mObserver.onScroll(deltaY);
}
mTrackedChildPrevTop = top;
} else {
mTrackedChild = null;
}
}
}
private View getChildInTheMiddle() {
return getChildAt(getChildCount() / 2);
}
public void setObserver(ListViewObserver observer) {
mObserver = observer;
}
public RefreshableListView(final Context context) {
super(context);
initialize();
}
public RefreshableListView(final Context context, final AttributeSet attrs) {
super(context, attrs);
initialize();
}
public RefreshableListView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void setOnRefreshListener(final OnRefreshListener l) {
mListener = l;
}
#Override
public void setOnTouchListener(OnTouchListener l) {
// TODO Auto-generated method stub
super.setOnTouchListener(l);
}
public void completeRefreshing() {
mProgress.setVisibility(View.INVISIBLE);
mArrow.setVisibility(View.VISIBLE);
mHandler.sendMessage(mHandler.obtainMessage(NORMAL, mHeaderHeight, 0));
mIsRefreshing = false;
invalidateViews();
}
#Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mHandler.removeMessages(REFRESH);
mHandler.removeMessages(NORMAL);
mY = mHistoricalY = ev.getY();
if (mHeaderContainer.getLayoutParams() != null) {
mInitialHeight = mHeaderContainer.getLayoutParams().height;
}
break;
}
return super.onInterceptTouchEvent(ev);
}
#Override
public boolean onTouchEvent(final MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
mHistoricalTop = getChildAt(0).getTop();
break;
case MotionEvent.ACTION_UP:
if (!mIsRefreshing) {
if (mArrowUp) {
startRefreshing();
mHandler.sendMessage(mHandler.obtainMessage(REFRESH,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
} else {
if (getChildAt(0).getTop() == 0) {
mHandler.sendMessage(mHandler.obtainMessage(NORMAL,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
}
}
} else {
mHandler.sendMessage(mHandler.obtainMessage(REFRESH,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
}
mFlag = false;
break;
}
return super.onTouchEvent(ev);
}
#Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_MOVE
&& getFirstVisiblePosition() == 0) {
float direction = ev.getY() - mHistoricalY;
int height = (int) (ev.getY() - mY) / 2 + mInitialHeight;
if (height < 0) {
height = 0;
}
float deltaY = Math.abs(mY - ev.getY());
ViewConfiguration config = ViewConfiguration.get(getContext());
if (deltaY > config.getScaledTouchSlop()) {
// Scrolling downward
if (direction > 0) {
// Refresh bar is extended if top pixel of the first item is
// visible
if (getChildAt(0) != null) {
if (getChildAt(0).getTop() == 0) {
if (mHistoricalTop < 0) {
// mY = ev.getY(); // TODO works without
// this?mHistoricalTop = 0;
}
// if (isScrool == true) {
//
// } else {
// isScrool = true;
// addHeaderView(vHeader);
//
// // Animation anim = AnimationUtils.loadAnimation(
// // getContext(), R.anim.bounce_animation);
// // startAnimation(anim);
//
// smoothScrollToPosition(getChildAt(0).getTop());
// // bottom_layout.setVisibility(View.VISIBLE);
// }
// Extends refresh bar
/*****
* commented by me on 10-09-2014
*/
setHeaderHeight(height);
// Stop list scroll to prevent the list from
// overscrolling
ev.setAction(MotionEvent.ACTION_CANCEL);
mFlag = false;
}
}
} else if (direction < 0) {
// Scrolling upward
// Refresh bar is shortened if top pixel of the first item
// is
// visible
if (getChildAt(0) != null) {
if (getChildAt(0).getTop() == 0) {
setHeaderHeight(height);
// If scroll reaches top of the list, list scroll is
// enabled
if (getChildAt(1) != null
&& getChildAt(1).getTop() <= 1 && !mFlag) {
ev.setAction(MotionEvent.ACTION_DOWN);
mFlag = true;
}
}
}
}
}
mHistoricalY = ev.getY();
}
try {
return super.dispatchTouchEvent(ev);
} catch (Exception e) {
return false;
}
}
#Override
public boolean performItemClick(final View view, final int position,
final long id) {
if (position == 0) {
// This is the refresh header element
return true;
} else {
return super.performItemClick(view, position - 1, id);
}
}
private void initialize() {
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vHeader = inflator.inflate(R.layout.search_header, null);
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mHeaderContainer = inflater.inflate(R.layout.refreshable_list_header,
null);
mHeaderView = mHeaderContainer
.findViewById(R.id.refreshable_list_header);
mArrow = (ImageView) mHeaderContainer
.findViewById(R.id.refreshable_list_arrow);
mProgress = (ProgressBar) mHeaderContainer
.findViewById(R.id.refreshable_list_progress);
mText = (TextView) mHeaderContainer
.findViewById(R.id.refreshable_list_text);
addHeaderView(mHeaderContainer);
mHeaderHeight = (int) (HEADER_HEIGHT_DP * getContext().getResources()
.getDisplayMetrics().density);
setHeaderHeight(0);
}
private void setHeaderHeight(final int height) {
if (height <= 1) {
mHeaderView.setVisibility(View.GONE);
} else {
mHeaderView.setVisibility(View.VISIBLE);
}
// Extends refresh bar
LayoutParams lp = (LayoutParams) mHeaderContainer.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
}
lp.height = height;
mHeaderContainer.setLayoutParams(lp);
// Refresh bar shows up from bottom to top
LinearLayout.LayoutParams headerLp = (LinearLayout.LayoutParams) mHeaderView
.getLayoutParams();
if (headerLp == null) {
headerLp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
}
headerLp.topMargin = -mHeaderHeight + height;
mHeaderView.setLayoutParams(headerLp);
if (!mIsRefreshing) {
// If scroll reaches the trigger line, start refreshing
if (height > mHeaderHeight && !mArrowUp) {
mArrow.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.rotate));
mText.setText("Release to update");
rotateArrow();
mArrowUp = true;
} else if (height < mHeaderHeight && mArrowUp) {
mArrow.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.rotate));
mText.setText("Pull down to update");
rotateArrow();
mArrowUp = false;
}else {
if (isScrool == true) {
} else {
isScrool = true;
addHeaderView(vHeader);
// Animation anim = AnimationUtils.loadAnimation(
// getContext(), R.anim.bounce_animation);
// startAnimation(anim);
smoothScrollToPosition(getChildAt(0).getTop());
// bottom_layout.setVisibility(View.VISIBLE);
}
}
}
}
private void rotateArrow() {
Drawable drawable = mArrow.getDrawable();
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.save();
canvas.rotate(180.0f, canvas.getWidth() / 2.0f,
canvas.getHeight() / 2.0f);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
canvas.restore();
mArrow.setImageBitmap(bitmap);
}
private void startRefreshing() {
mArrow.setVisibility(View.INVISIBLE);
mProgress.setVisibility(View.VISIBLE);
mText.setText("Loading...");
mIsRefreshing = true;
if (mListener != null) {
mListener.onRefresh(this);
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
int limit = 0;
switch (msg.what) {
case REFRESH:
limit = mHeaderHeight;
break;
case NORMAL:
limit = 0;
break;
}
// Elastic scrolling
if (msg.arg1 >= limit) {
setHeaderHeight(msg.arg1);
int displacement = (msg.arg1 - limit) / 10;
if (displacement == 0) {
mHandler.sendMessage(mHandler.obtainMessage(msg.what,
msg.arg1 - 1, 0));
} else {
mHandler.sendMessage(mHandler.obtainMessage(msg.what,
msg.arg1 - displacement, 0));
}
}
}
};
public interface OnRefreshListener {
public void onRefresh(RefreshableListView listView);
}
public static interface ListViewObserver {
public void onScroll(float deltaY);
}
}
here in method dispatchTouchEvent(final MotionEvent ev) i have make one condition
if (isScrool == true) {
} else {
isScrool = true;
addHeaderView(vHeader);
// Animation anim =
// AnimationUtils.loadAnimation(
// getContext(), R.anim.bounce_animation);
// startAnimation(anim);
smoothScrollToPosition(getChildAt(0).getTop());
// bottom_layout.setVisibility(View.VISIBLE);
}
here addHeaderView(vHeader);
adds header but my listview scroll down to last item can anyone could tell me what's happening here?
Try to call listView.setSelectionAfterHeaderView();. This will scroll ListView to top.

Refreshing Custom Listview with holder ClassCastException

i`m doing a Custom listview with holder.it is perfectly loaded but while i refresh the data by pull down the application is force closing please help
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// View rowView = convertView;
// String record = (String) getItem(position);
// LayoutInflater inflater = Test_home.this.getLayoutInflater();
LayoutInflater inflater = Test_home.this.getLayoutInflater();
ViewHolder holder = new ViewHolder();
if (convertView == null) {
// LayoutInflater vi = (LayoutInflater)
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.claim_list, null);
holder = new ViewHolder();
holder.claim_list_layout = (LinearLayout) convertView
.findViewById(R.id.claim_list_layout);
holder.claimnumb = (TextView) convertView
.findViewById(R.id.claimnumb);
holder.insuerdname = (TextView) convertView
.findViewById(R.id.insuerdname);
holder.claimaddress = (TextView) convertView
.findViewById(R.id.claimaddress);
holder.btn_start = (Button) convertView
.findViewById(R.id.btn_start);
convertView.setTag(holder);
}
final ViewHolder holder1 = (ViewHolder) convertView.getTag();
// holder = (ViewHolder) convertView.getTag();
final Claim_list claim_option = claim_list_adaptor.get(position);
holder1.claimnumb.setText(claim_option.getClaimNumber());
holder1.insuerdname.setText(claim_option.getInsuredName());
holder1.claimaddress.setText(claim_option.getPropertyAddress());
// Tag Setting
holder1.claimnumb.setTag(claim_option);
holder1.insuerdname.setTag(claim_option);
holder1.claimaddress.setTag(claim_option);
holder1.claim_list_layout.setTag(claim_option);
holder1.btn_start.setTag(claim_option);
holder1.btn_start.setVisibility(View.GONE);
if (position == 0 && isoncreate) {
isoncreate = false;
holder1.claim_list_layout
.setBackgroundResource(R.drawable.claim_list_active);
holder1.btn_start.setVisibility(View.VISIBLE);
beanclass.setClaim_info_header("Claim: "
+ claim_option.getClaimNumber() + " / "
+ claim_option.getInsuredName());
TV_claiminfo.setText(beanclass.getClaim_info_header());
} else {
holder1.claim_list_layout
.setBackgroundResource(R.drawable.claim_list_inactive);
}
return convertView;
}
This is the error
01-02 11:15:39.989: W/dalvikvm(14670): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-02 11:15:40.062: W/System.err(14670): java.lang.ClassCastException: com.wbpro.da.Claim_list cannot be cast to com.wbpro.flood.Test_home$PullToRefreshListViewSampleAdapter$ViewHolder
01-02 11:15:40.085: W/System.err(14670): at com.wbpro.flood.Test_home$PullToRefreshListViewSampleAdapter.getView(Test_home.java:437)
01-02 11:15:40.085: W/System.err(14670): at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
And i`m using the Custom widget for list view
<com.example.pul.PullToRefreshListView
android:id="#+id/pull_to_refresh_listview"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/white"
android:cacheColorHint="#android:color/white" />
This is the custom class
public class PullToRefreshListView extends ListView {
private static final float PULL_RESISTANCE = 1.7f;
private static final int BOUNCE_ANIMATION_DURATION = 700;
private static final int BOUNCE_ANIMATION_DELAY = 100;
private static final float BOUNCE_OVERSHOOT_TENSION = 1.4f;
private static final int ROTATE_ARROW_ANIMATION_DURATION = 250;
private static enum State {
PULL_TO_REFRESH, RELEASE_TO_REFRESH, REFRESHING
}
/**
* Interface to implement when you want to get notified of 'pull to refresh'
* events. Call setOnRefreshListener(..) to activate an OnRefreshListener.
*/
public interface OnRefreshListener {
/**
* Method to be called when a refresh is requested
*/
public void onRefresh();
}
private static int measuredHeaderHeight;
private boolean scrollbarEnabled;
private boolean bounceBackHeader;
private boolean lockScrollWhileRefreshing;
private boolean showLastUpdatedText;
private String pullToRefreshText;
private String releaseToRefreshText;
private String refreshingText;
private String lastUpdatedText;
private SimpleDateFormat lastUpdatedDateFormat = new SimpleDateFormat(
"dd/MM HH:mm");
private float previousY;
private int headerPadding;
private boolean hasResetHeader;
private long lastUpdated = -1;
private State state;
private LinearLayout headerContainer;
private RelativeLayout header;
private RotateAnimation flipAnimation;
private RotateAnimation reverseFlipAnimation;
private ImageView image;
private ProgressBar spinner;
private TextView text;
private TextView lastUpdatedTextView;
private OnItemClickListener onItemClickListener;
private OnItemLongClickListener onItemLongClickListener;
private OnRefreshListener onRefreshListener;
private float mScrollStartY;
private final int IDLE_DISTANCE = 5;
public PullToRefreshListView(Context context) {
super(context);
init();
}
public PullToRefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PullToRefreshListView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init();
}
#Override
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#Override
public void setOnItemLongClickListener(
OnItemLongClickListener onItemLongClickListener) {
this.onItemLongClickListener = onItemLongClickListener;
}
/**
* Activate an OnRefreshListener to get notified on 'pull to refresh'
* events.
*
* #param onRefreshListener
* The OnRefreshListener to get notified
*/
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
this.onRefreshListener = onRefreshListener;
}
/**
* #return If the list is in 'Refreshing' state
*/
public boolean isRefreshing() {
return state == State.REFRESHING;
}
/**
* Default is false. When lockScrollWhileRefreshing is set to true, the list
* cannot scroll when in 'refreshing' mode. It's 'locked' on refreshing.
*
* #param lockScrollWhileRefreshing
*/
public void setLockScrollWhileRefreshing(boolean lockScrollWhileRefreshing) {
this.lockScrollWhileRefreshing = lockScrollWhileRefreshing;
}
/**
* Default is false. Show the last-updated date/time in the 'Pull ro
* Refresh' header. See 'setLastUpdatedDateFormat' to set the date/time
* formatting.
*
* #param showLastUpdatedText
*/
public void setShowLastUpdatedText(boolean showLastUpdatedText) {
this.showLastUpdatedText = showLastUpdatedText;
if (!showLastUpdatedText)
lastUpdatedTextView.setVisibility(View.GONE);
}
/**
* Default: "dd/MM HH:mm". Set the format in which the last-updated
* date/time is shown. Meaningless if 'showLastUpdatedText == false
* (default)'. See 'setShowLastUpdatedText'.
*
* #param lastUpdatedDateFormat
*/
public void setLastUpdatedDateFormat(SimpleDateFormat lastUpdatedDateFormat) {
this.lastUpdatedDateFormat = lastUpdatedDateFormat;
}
/**
* Explicitly set the state to refreshing. This is useful when you want to
* show the spinner and 'Refreshing' text when the refresh was not triggered
* by 'pull to refresh', for example on start.
*/
public void setRefreshing() {
state = State.REFRESHING;
scrollTo(0, 0);
setUiRefreshing();
setHeaderPadding(0);
}
/**
* Set the state back to 'pull to refresh'. Call this method when refreshing
* the data is finished.
*/
public void onRefreshComplete() {
state = State.PULL_TO_REFRESH;
resetHeader();
lastUpdated = System.currentTimeMillis();
}
/**
* Change the label text on state 'Pull to Refresh'
*
* #param pullToRefreshText
* Text
*/
public void setTextPullToRefresh(String pullToRefreshText) {
this.pullToRefreshText = pullToRefreshText;
if (state == State.PULL_TO_REFRESH) {
text.setText(pullToRefreshText);
}
}
/**
* Change the label text on state 'Release to Refresh'
*
* #param releaseToRefreshText
* Text
*/
public void setTextReleaseToRefresh(String releaseToRefreshText) {
this.releaseToRefreshText = releaseToRefreshText;
if (state == State.RELEASE_TO_REFRESH) {
text.setText(releaseToRefreshText);
}
}
/**
* Change the label text on state 'Refreshing'
*
* #param refreshingText
* Text
*/
public void setTextRefreshing(String refreshingText) {
this.refreshingText = refreshingText;
if (state == State.REFRESHING) {
text.setText(refreshingText);
}
}
private void init() {
setVerticalFadingEdgeEnabled(false);
headerContainer = (LinearLayout) LayoutInflater.from(getContext())
.inflate(R.layout.ptr_header, null);
header = (RelativeLayout) headerContainer
.findViewById(R.id.ptr_id_header);
text = (TextView) header.findViewById(R.id.ptr_id_text);
lastUpdatedTextView = (TextView) header
.findViewById(R.id.ptr_id_last_updated);
image = (ImageView) header.findViewById(R.id.ptr_id_image);
spinner = (ProgressBar) header.findViewById(R.id.ptr_id_spinner);
pullToRefreshText = getContext()
.getString(R.string.ptr_pull_to_refresh);
releaseToRefreshText = getContext().getString(
R.string.ptr_release_to_refresh);
refreshingText = getContext().getString(R.string.ptr_refreshing);
lastUpdatedText = getContext().getString(R.string.ptr_last_updated);
flipAnimation = new RotateAnimation(0, -180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
flipAnimation.setInterpolator(new LinearInterpolator());
flipAnimation.setDuration(ROTATE_ARROW_ANIMATION_DURATION);
flipAnimation.setFillAfter(true);
reverseFlipAnimation = new RotateAnimation(-180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
reverseFlipAnimation.setInterpolator(new LinearInterpolator());
reverseFlipAnimation.setDuration(ROTATE_ARROW_ANIMATION_DURATION);
reverseFlipAnimation.setFillAfter(true);
addHeaderView(headerContainer);
setState(State.PULL_TO_REFRESH);
scrollbarEnabled = isVerticalScrollBarEnabled();
ViewTreeObserver vto = header.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new PTROnGlobalLayoutListener());
super.setOnItemClickListener(new PTROnItemClickListener());
super.setOnItemLongClickListener(new PTROnItemLongClickListener());
}
private void setHeaderPadding(int padding) {
headerPadding = padding;
MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) header
.getLayoutParams();
mlp.setMargins(0, Math.round(padding), 0, 0);
header.setLayoutParams(mlp);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (lockScrollWhileRefreshing
&& (state == State.REFRESHING || getAnimation() != null
&& !getAnimation().hasEnded())) {
return true;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (getFirstVisiblePosition() == 0) {
previousY = event.getY();
} else {
previousY = -1;
}
// Remember where have we started
mScrollStartY = event.getY();
break;
case MotionEvent.ACTION_UP:
if (previousY != -1
&& (state == State.RELEASE_TO_REFRESH || getFirstVisiblePosition() == 0)) {
switch (state) {
case RELEASE_TO_REFRESH:
setState(State.REFRESHING);
bounceBackHeader();
break;
case PULL_TO_REFRESH:
resetHeader();
break;
}
}
break;
case MotionEvent.ACTION_MOVE:
if (previousY != -1 && getFirstVisiblePosition() == 0
&& Math.abs(mScrollStartY - event.getY()) > IDLE_DISTANCE) {
float y = event.getY();
float diff = y - previousY;
if (diff > 0)
diff /= PULL_RESISTANCE;
previousY = y;
int newHeaderPadding = Math.max(
Math.round(headerPadding + diff), -header.getHeight());
if (newHeaderPadding != headerPadding
&& state != State.REFRESHING) {
setHeaderPadding(newHeaderPadding);
if (state == State.PULL_TO_REFRESH && headerPadding > 0) {
setState(State.RELEASE_TO_REFRESH);
image.clearAnimation();
image.startAnimation(flipAnimation);
} else if (state == State.RELEASE_TO_REFRESH
&& headerPadding < 0) {
setState(State.PULL_TO_REFRESH);
image.clearAnimation();
image.startAnimation(reverseFlipAnimation);
}
}
}
break;
}
return super.onTouchEvent(event);
}
private void bounceBackHeader() {
int yTranslate = state == State.REFRESHING ? header.getHeight()
- headerContainer.getHeight() : -headerContainer.getHeight()
- headerContainer.getTop() + getPaddingTop();
;
TranslateAnimation bounceAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0, TranslateAnimation.ABSOLUTE, 0,
TranslateAnimation.ABSOLUTE, 0, TranslateAnimation.ABSOLUTE,
yTranslate);
bounceAnimation.setDuration(BOUNCE_ANIMATION_DURATION);
bounceAnimation.setFillEnabled(true);
bounceAnimation.setFillAfter(false);
bounceAnimation.setFillBefore(true);
bounceAnimation.setInterpolator(new OvershootInterpolator(
BOUNCE_OVERSHOOT_TENSION));
bounceAnimation.setAnimationListener(new HeaderAnimationListener(
yTranslate));
startAnimation(bounceAnimation);
}
private void resetHeader() {
if (getFirstVisiblePosition() > 0) {
setHeaderPadding(-header.getHeight());
setState(State.PULL_TO_REFRESH);
return;
}
if (getAnimation() != null && !getAnimation().hasEnded()) {
bounceBackHeader = true;
} else {
bounceBackHeader();
}
}
private void setUiRefreshing() {
spinner.setVisibility(View.VISIBLE);
image.clearAnimation();
image.setVisibility(View.INVISIBLE);
text.setText(refreshingText);
}
private void setState(State state) {
this.state = state;
switch (state) {
case PULL_TO_REFRESH:
spinner.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
text.setText(pullToRefreshText);
if (showLastUpdatedText && lastUpdated != -1) {
lastUpdatedTextView.setVisibility(View.VISIBLE);
lastUpdatedTextView.setText(String.format(lastUpdatedText,
lastUpdatedDateFormat.format(new Date(lastUpdated))));
}
break;
case RELEASE_TO_REFRESH:
spinner.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
text.setText(releaseToRefreshText);
break;
case REFRESHING:
setUiRefreshing();
lastUpdated = System.currentTimeMillis();
if (onRefreshListener == null) {
setState(State.PULL_TO_REFRESH);
} else {
onRefreshListener.onRefresh();
}
break;
}
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (!hasResetHeader) {
if (measuredHeaderHeight > 0 && state != State.REFRESHING) {
setHeaderPadding(-measuredHeaderHeight);
}
hasResetHeader = true;
}
}
private class HeaderAnimationListener implements AnimationListener {
private int height, translation;
private State stateAtAnimationStart;
public HeaderAnimationListener(int translation) {
this.translation = translation;
}
#Override
public void onAnimationStart(Animation animation) {
stateAtAnimationStart = state;
android.view.ViewGroup.LayoutParams lp = getLayoutParams();
height = lp.height;
lp.height = getHeight() - translation;
setLayoutParams(lp);
if (scrollbarEnabled) {
setVerticalScrollBarEnabled(false);
}
}
#Override
public void onAnimationEnd(Animation animation) {
setHeaderPadding(stateAtAnimationStart == State.REFRESHING ? 0
: -measuredHeaderHeight - headerContainer.getTop());
setSelection(0);
android.view.ViewGroup.LayoutParams lp = getLayoutParams();
lp.height = height;
setLayoutParams(lp);
if (scrollbarEnabled) {
setVerticalScrollBarEnabled(true);
}
if (bounceBackHeader) {
bounceBackHeader = false;
postDelayed(new Runnable() {
#Override
public void run() {
resetHeader();
}
}, BOUNCE_ANIMATION_DELAY);
} else if (stateAtAnimationStart != State.REFRESHING) {
setState(State.PULL_TO_REFRESH);
}
}
#Override
public void onAnimationRepeat(Animation animation) {
}
}
private class PTROnGlobalLayoutListener implements OnGlobalLayoutListener {
#Override
public void onGlobalLayout() {
int initialHeaderHeight = header.getHeight();
if (initialHeaderHeight > 0) {
measuredHeaderHeight = initialHeaderHeight;
if (measuredHeaderHeight > 0 && state != State.REFRESHING) {
setHeaderPadding(-measuredHeaderHeight);
requestLayout();
}
}
getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
private class PTROnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
hasResetHeader = false;
if (onItemClickListener != null && state == State.PULL_TO_REFRESH) {
// Passing up onItemClick. Correct position with the number of
// header views
onItemClickListener.onItemClick(adapterView, view, position
- getHeaderViewsCount(), id);
}
}
}
private class PTROnItemLongClickListener implements OnItemLongClickListener {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
int position, long id) {
hasResetHeader = false;
if (onItemLongClickListener != null
&& state == State.PULL_TO_REFRESH) {
// Passing up onItemLongClick. Correct position with the number
// of header views
return onItemLongClickListener.onItemLongClick(adapterView,
view, position - getHeaderViewsCount(), id);
}
return false;
}
}
}
i had populated the data fine. but the problem is when is refresh the adaptor.
listView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
adapter.loadData();
listView.postDelayed(new Runnable() {
#Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
}
});
ArrayList<Claim_list> claim_list_adaptor = Claim_list.getItems("0", Test_home.this);
Put the else to get the tag of your views and remove the code of setting the tags again.
Try to change the code of your getView() method as below:
if (convertView == null) {
// LayoutInflater vi = (LayoutInflater)
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.claim_list, null);
holder = new ViewHolder();
holder.claim_list_layout = (LinearLayout) convertView
.findViewById(R.id.claim_list_layout);
holder.claimnumb = (TextView) convertView
.findViewById(R.id.claimnumb);
holder.insuerdname = (TextView) convertView
.findViewById(R.id.insuerdname);
holder.claimaddress = (TextView) convertView
.findViewById(R.id.claimaddress);
holder.btn_start = (Button) convertView
.findViewById(R.id.btn_start);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
final Claim_list claim_option = claim_list_adaptor.get(position);
holder1.claimnumb.setText(claim_option.getClaimNumber());
holder1.insuerdname.setText(claim_option.getInsuredName());
holder1.claimaddress.setText(claim_option.getPropertyAddress());
holder1.btn_start.setVisibility(View.GONE);
if (position == 0 && isoncreate) {
isoncreate = false;
holder1.claim_list_layout
.setBackgroundResource(R.drawable.claim_list_active);
holder1.btn_start.setVisibility(View.VISIBLE);
beanclass.setClaim_info_header("Claim: "
+ claim_option.getClaimNumber() + " / "
+ claim_option.getInsuredName());
TV_claiminfo.setText(beanclass.getClaim_info_header());
} else {
holder1.claim_list_layout
.setBackgroundResource(R.drawable.claim_list_inactive);
}
return convertView;
}
holder1.claimnumb.setTag(claim_option);
holder1.insuerdname.setTag(claim_option);
holder1.claimaddress.setTag(claim_option);
holder1.claim_list_layout.setTag(claim_option);
holder1.btn_start.setTag(claim_option);
These statements are creating problem for Class-cast Exception , you should not cast the holder again. Use a single reference for holder.
Use this code
if (convertView == null) {
// LayoutInflater vi = (LayoutInflater)
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.claim_list, null);
holder = new ViewHolder();
holder.claim_list_layout = (LinearLayout) convertView
.findViewById(R.id.claim_list_layout);
holder.claimnumb = (TextView) convertView
.findViewById(R.id.claimnumb);
holder.insuerdname = (TextView) convertView
.findViewById(R.id.insuerdname);
holder.claimaddress = (TextView) convertView
.findViewById(R.id.claimaddress);
holder.btn_start = (Button) convertView
.findViewById(R.id.btn_start);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
final Claim_list claim_option = claim_list_adaptor.get(position);
holder.claimnumb.setText(claim_option.getClaimNumber());
holder.insuerdname.setText(claim_option.getInsuredName());
holder.claimaddress.setText(claim_option.getPropertyAddress());
holder.btn_start.setVisibility(View.GONE);
if (position == 0 && isoncreate) {
isoncreate = false;
holder.claim_list_layout
.setBackgroundResource(R.drawable.claim_list_active);
holder.btn_start.setVisibility(View.VISIBLE);
beanclass.setClaim_info_header("Claim: "
+ claim_option.getClaimNumber() + " / "
+ claim_option.getInsuredName());
TV_claiminfo.setText(beanclass.getClaim_info_header());
} else {
holder.claim_list_layout
.setBackgroundResource(R.drawable.claim_list_inactive);
}
return convertView;
}
And to refresh just take updated data on your array list and call notifyDataSetchanged method of your adapter. Make sure dont use new instance of your adapter.

Categories

Resources