Im using a ViewPager to show Images. The ViewPager is working correctly but there is an error with the indicator. When i swipe to the very last entry the indicator is only at round about 70% of the way. See the screen:
That is the problem. I dont know if the indicator is just too small, moving to slow or there are another hidden entries in the viewpager but since i cant swipe any further to the right i guess there is a bug with the indicator size or moving or something like that.
This is how i initializ my viewpager:
this.viewPager.setId(R.id.image_inspiration_pager);
this.viewPager.setClipToPadding(false);
this.viewPager.setPadding(0, 0, ((int) HelperPixel.convertDpToPixel(this.getContext(), 48)), 0);
this.viewPager.setAdapter(adapter);
this.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private static final float thresholdOffset = 0.5f;
private boolean scrollStarted = false;
private boolean checkDirection = false;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
viewPager.setPadding(0, 0, ((int) HelperPixel.convertDpToPixel(getContext(), 48)), 0);
return;
} else if (position == (adapter.getCount() - 1)) {
viewPager.setPadding(((int) HelperPixel.convertDpToPixel(getContext(), 48)), 0, 0, 0);
return;
}
if (this.checkDirection) {
if (thresholdOffset > positionOffset) {
viewPager.setPadding(0, 0, ((int) HelperPixel.convertDpToPixel(getContext(), 48)), 0);
} else {
viewPager.setPadding(((int) HelperPixel.convertDpToPixel(getContext(), 48)), 0, 0, 0);
}
this.checkDirection = false;
}
}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {
if (!this.scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
this.scrollStarted = true;
this.checkDirection = true;
} else {
this.scrollStarted = false;
}
}
});
Implementation of TabLayout:
public class TabsSlidingLayout extends HorizontalScrollView {
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 14;
private int titleOffset;
private int tabViewLayoutId;
private int tabViewTextViewId;
private ViewPager viewPager;
private ViewPager.OnPageChangeListener pageChangeListener;
private final TabsSlidingStrip tabStrip;
public TabsSlidingLayout(Context context) {
this(context, null);
}
public TabsSlidingLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TabsSlidingLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setHorizontalScrollBarEnabled(false);
this.setFillViewport(true);
this.titleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
this.tabStrip = new TabsSlidingStrip(context);
this.addView(this.tabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
public void setCustomBackgroundColor(int color) {
this.tabStrip.setBackgroundColor(color);
}
public void setCustomTabColorizer(TabColorizer tabColorizer) {
this.tabStrip.setCustomTabColorizer(tabColorizer);
}
public void setSelectedIndicatorColors(int... colors) {
this.tabStrip.setSelectedIndicatorColors(colors);
}
public void setDividerColors(int... colors) {
this.tabStrip.setDividerColors(colors);
}
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
this.pageChangeListener = listener;
}
public void setCustomTabView(int layoutResId, int textViewId) {
this.tabViewLayoutId = layoutResId;
this.tabViewTextViewId = textViewId;
}
public void setViewPager(ViewPager viewPager) {
this.tabStrip.removeAllViews();
this.viewPager = viewPager;
if (this.viewPager != null) {
this.viewPager.addOnPageChangeListener(new InternalViewPagerListener());
this.populateTabStrip();
}
}
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setTextColor(ContextCompat.getColor(context, R.color.white));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
TypedValue outValue = new TypedValue();
this.getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
textView.setBackgroundResource(outValue.resourceId);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
textView.setAllCaps(true);
}
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = this.viewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (this.tabViewLayoutId != 0) {
tabView = LayoutInflater.from(this.getContext()).inflate(this.tabViewLayoutId, this.tabStrip, false);
tabTitleView = (TextView) tabView.findViewById(this.tabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(this.getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
this.tabStrip.addView(tabView);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (this.viewPager != null) {
this.scrollToTab(this.viewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = this.tabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = this.tabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
targetScrollX -= this.titleOffset;
}
this.scrollTo(targetScrollX, 0);
}
}
public interface TabColorizer {
int getIndicatorColor(int position);
int getDividerColor(int position);
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int scrollState = -1;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = tabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
tabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = tabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWidth()) : 0;
scrollToTab(position, extraOffset);
if (pageChangeListener != null) {
pageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
this.scrollState = state;
if (pageChangeListener != null) {
pageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (this.scrollState == ViewPager.SCROLL_STATE_IDLE) {
tabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
if (pageChangeListener != null) {
pageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View view) {
for (int i = 0; i < tabStrip.getChildCount(); i++) {
if (view == tabStrip.getChildAt(i)) {
viewPager.setCurrentItem(i);
return;
}
}
}
}
}
TabSlidingStrip implementation:
class TabsSlidingStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 2;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFFFFFFFF;
private static final int DEFAULT_DIVIDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_DIVIDER_COLOR_ALPHA = 0x20;
private static final float DEFAULT_DIVIDER_HEIGHT = 0.0f;
private final int bottomBorderThickness;
private final Paint bottomBorderPaint;
private final int selectedIndicatorThickness;
private final Paint selectedIndicatorPaint;
private final Paint dividerPaint;
private final float dividerHeight;
private int selectedPosition;
private float selectionOffset;
private TabsSlidingLayout.TabColorizer customTabColorizer;
private final SimpleTabColorizer defaultTabColorizer;
public TabsSlidingStrip(Context context) {
this(context, null);
}
public TabsSlidingStrip(Context context, AttributeSet attrs) {
super(context, attrs);
this.setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
final int themeForegroundColor = outValue.data;
this.setBackgroundColor(ContextCompat.getColor(context, R.color.primaryColor));
this.defaultTabColorizer = new SimpleTabColorizer();
this.defaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
this.defaultTabColorizer.setDividerColors(setColorAlpha(themeForegroundColor, DEFAULT_DIVIDER_COLOR_ALPHA));
this.bottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
this.bottomBorderPaint = new Paint();
this.bottomBorderPaint.setColor(setColorAlpha(themeForegroundColor, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA));
this.selectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
this.selectedIndicatorPaint = new Paint();
this.dividerHeight = DEFAULT_DIVIDER_HEIGHT;
this.dividerPaint = new Paint();
this.dividerPaint.setStrokeWidth((int) (DEFAULT_DIVIDER_THICKNESS_DIPS * density));
}
void setCustomTabColorizer(TabsSlidingLayout.TabColorizer customTabColorizer) {
this.customTabColorizer = customTabColorizer;
this.invalidate();
}
void setSelectedIndicatorColors(int... colors) {
this.customTabColorizer = null;
this.defaultTabColorizer.setIndicatorColors(colors);
this.invalidate();
}
void setDividerColors(int... colors) {
this.customTabColorizer = null;
this.defaultTabColorizer.setDividerColors(colors);
this.invalidate();
}
void onViewPagerPageChanged(int position, float positionOffset) {
this.selectedPosition = position;
this.selectionOffset = positionOffset;
this.invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
final int height = this.getHeight();
final int childCount = this.getChildCount();
final int dividerHeightPx = (int) (Math.min(Math.max(0f, this.dividerHeight), 1f) * height);
final TabsSlidingLayout.TabColorizer tabColorizer = this.customTabColorizer != null ? this.customTabColorizer : this.defaultTabColorizer;
if (childCount > 0) {
View selectedTitle = getChildAt(this.selectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(this.selectedPosition);
if (this.selectionOffset > 0f && this.selectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(this.selectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, this.selectionOffset);
}
View nextTitle = getChildAt(this.selectedPosition + 1);
left = (int) (this.selectionOffset * nextTitle.getLeft() + (1.0f - this.selectionOffset) * left);
right = (int) (this.selectionOffset * nextTitle.getRight() + (1.0f - this.selectionOffset) * right);
}
this.selectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - this.selectedIndicatorThickness, right, height, this.selectedIndicatorPaint);
}
canvas.drawRect(0, height - this.bottomBorderThickness, this.getWidth(), height, this.bottomBorderPaint);
int separatorTop = (height - dividerHeightPx) / 2;
for (int i = 0; i < childCount - 1; i++) {
View child = getChildAt(i);
this.dividerPaint.setColor(tabColorizer.getDividerColor(i));
canvas.drawLine(child.getRight(), separatorTop, child.getRight(), separatorTop + dividerHeightPx, this.dividerPaint);
}
}
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements TabsSlidingLayout.TabColorizer {
private int[] indicatorColors;
private int[] dividerColors;
#Override
public final int getIndicatorColor(int position) {
return this.indicatorColors[position % this.indicatorColors.length];
}
void setIndicatorColors(int... colors) {
this.indicatorColors = colors;
}
#Override
public final int getDividerColor(int position) {
return this.dividerColors[position % this.dividerColors.length];
}
void setDividerColors(int... colors) {
this.dividerColors = colors;
}
}
}
The first screenshot is from a tablet. Here is a screen from my smartphone:
As you can see for the smartphone the gap is much smaller than on the tablet.
Any idea what could be the problem?
Add the following code to the bottom of createDefaultTabView:
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
textView.setWidth(size.x / this.viewPager.getAdapter().getCount());
Related
I have a custom switch button which i am using for attendance purpose.I am saving the value in shared prefernces.the values are being retrieved very well but the state of the switch button needs to be changed on create according to value of shared preferences.For example if the value is true then button will be in unchecked state and if false button will be in checked state.how to achieve this?
getPreference();
if(Common.punchedIn) {
// switchButton.setOnCheckedChangeListener(null);
switchButton.setChecked(false);
}
else
{
// switchButton.setOnCheckedChangeListener(null);
switchButton.setChecked(true);
}
switchButton.setOnCheckedChangeListener(new MySwitchButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(MySwitchButton s, boolean isChecked) {
if(switchButton.isChecked()){
String acTime = getActionTime();
String acDate = getActionDate();
String loc = getGPSLocation();
String empID = getEmployeeID();
String empReportingTo = getReportingTo();
//Toast.makeText(AttendanceActivity.this, "Switch is currently ON", Toast.LENGTH_LONG).show();
punchStatus_text.setText("Punch Out");
shift_dur_text.setVisibility(View.INVISIBLE);
shift_dur_time.setVisibility(View.INVISIBLE);
checkin_time.setVisibility(View.VISIBLE);
checkin_time.setText("Check in :"+acTime);
checkout_time.setVisibility(View.INVISIBLE);
saveAttendance(empID,empReportingTo,acDate,acTime,loc,"na","na","IN");
}else{
String acTime = getActionTime();
String acDate = getActionDate();
String loc = getGPSLocation();
String empID = getEmployeeID();
String empReportingTo = getReportingTo();
//Toast.makeText(AttendanceActivity.this, "Switch is currently OFF", Toast.LENGTH_LONG).show();
punchStatus_text.setText("Punch In");
shift_dur_text.setVisibility(View.VISIBLE);
shift_dur_time.setVisibility(View.VISIBLE);
checkin_time.setText("Check in :"+Common.punchInTime);
checkin_time.setVisibility(View.INVISIBLE);
checkout_time.setVisibility(View.VISIBLE);
checkout_time.setText("Check Out:"+acTime);
saveAttendance(empID,empReportingTo,acDate,acTime,loc,"na","na","OUT");
}
}
});
saving and retrieving from share preference
public static boolean setPreference(Context context,boolean value) {
SharedPreferences settings = context.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("punch",value);
return editor.commit();
}
public void getPreference() {
SharedPreferences settings = this.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
// Toast.makeText(this,"EMP ID is "+emp_id,Toast.LENGTH_LONG).show();
Common.punchedIn = settings.getBoolean("punch", false);
Toast.makeText(this,"PUNCH IN STATUS "+String.valueOf(Common.punchedIn),Toast.LENGTH_LONG).show();
}
SWITCH BUTTON CLASS
public class MySwitchButton extends View implements Checkable {
private static final int ANIMATION_DURATION = 300;
private static final int DEFAULT_WIDTH = 100;
private static final int DEFAULT_HEIGHT = 50;
private static final int DEFAULT_SPOT_PADDING = 6;
private static final int DEFAULT_BORDER_WIDTH = 4;
private static final int DEFAULT_SWITCH_ON_COLOR = Color.LTGRAY;
private static final int DEFAULT_SWITCH_ON_COLOR_OUT = Color.LTGRAY;
private static final int DEFAULT_SWITCH_OFF_COLOR = Color.LTGRAY;
private static final int DEFAULT_SWITCH_OFF_COLOR_OUT = Color.LTGRAY;
private static final int DEFAULT_SPOT_ON_COLOR = R.color.colorBrown;
private static final int DEFAULT_SPOT_ON_COLOR_IN = R.color.colorBrown;
private static final int DEFAULT_SPOT_OFF_COLOR = R.color.colorBrown;
private static final int DEFAULT_SPOT_OFF_COLOR_IN = R.color.colorBrown;
private static final int SWITCH_OFF_POS = 0;
private static final int SWITCH_ON_POS = 1;
private int switchOnColor;
private int switchOffColor;
private int spotOnColor;
private int spotOnColorIn;
private int spotOffColor;
private int spotOffColorIn;
private int switchOnStrokeColor;
private int switchOffStrokeColor;
private int spotPadding;
private float currentPos;
private boolean mChecked;
private boolean mBroadcasting;
private boolean isMoving;
private int duration;
private OnCheckedChangeListener onCheckedChangeListener;
private ValueAnimator valueAnimator;
private enum State {
SWITCH_ANIMATION_OFF, SWITCH_ANIMATION_ON, SWITCH_ON, SWITCH_OFF
}
private State state;
public MySwitchButton(Context context) {
super(context);
switchOnColor = DEFAULT_SWITCH_ON_COLOR;
switchOffColor = DEFAULT_SWITCH_OFF_COLOR;
spotOnColor = DEFAULT_SPOT_ON_COLOR;
spotOnColorIn = DEFAULT_SPOT_ON_COLOR_IN;
spotOffColor = DEFAULT_SPOT_OFF_COLOR;
spotOffColorIn = DEFAULT_SPOT_OFF_COLOR_IN;
spotPadding = dp2px(DEFAULT_SPOT_PADDING);
switchOnStrokeColor = switchOnColor;
switchOffStrokeColor = switchOffColor;
duration = ANIMATION_DURATION;
state = mChecked ? State.SWITCH_ON : State.SWITCH_OFF;
setClickable(true);
}
public MySwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Switch);
switchOnColor = a.getColor(R.styleable.Switch_switchOnColor, DEFAULT_SWITCH_ON_COLOR);
switchOffColor = a.getColor(R.styleable.Switch_switchOffColor, DEFAULT_SWITCH_OFF_COLOR);
// switchOnColor = getResources().getColor(R.color.colorBrown);
//switchOffColor = getResources().getColor(R.color.colorBrown);
spotOnColor = a.getColor(R.styleable.Switch_spotOnColor, DEFAULT_SPOT_ON_COLOR);
spotOnColorIn = a.getColor(R.styleable.Switch_spotOnColor, DEFAULT_SPOT_ON_COLOR_IN);
spotOffColor = a.getColor(R.styleable.Switch_spotOffColor, DEFAULT_SPOT_OFF_COLOR);
spotOffColorIn = a.getColor(R.styleable.Switch_spotOnColor, DEFAULT_SPOT_OFF_COLOR_IN);
spotPadding = a.getDimensionPixelSize(R.styleable.Switch_spotPadding, dp2px(DEFAULT_SPOT_PADDING));
switchOnStrokeColor = a.getColor(R.styleable.Switch_switchOnStrokeColor, switchOnColor);
switchOffStrokeColor = a.getColor(R.styleable.Switch_switchOffStrokeColor, switchOffColor);
duration = a.getInteger(R.styleable.Switch_duration, ANIMATION_DURATION);
mChecked = a.getBoolean(R.styleable.Switch_checked, false);
a.recycle();
state = mChecked ? State.SWITCH_ON : State.SWITCH_OFF;
setClickable(true);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int width = dp2px(DEFAULT_WIDTH) + getPaddingLeft() + getPaddingRight();
int height = dp2px(DEFAULT_HEIGHT) + getPaddingTop() + getPaddingBottom();
if (widthSpecMode != MeasureSpec.AT_MOST) {
width = Math.max(width, widthSpecSize);
}
if (heightSpecMode != MeasureSpec.AT_MOST) {
height = Math.max(height, heightSpecSize);
}
setMeasuredDimension(width, height);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
int pl = getPaddingLeft();
int pt = getPaddingTop();
int pr = getPaddingRight();
int pb = getPaddingBottom();
int wp = w - pl - pr;
int hp = h - pt - pb;
int sw = dp2px(DEFAULT_WIDTH);
int sh = dp2px(DEFAULT_HEIGHT);
int dx = pl + (wp - sw) / 2;
int dy = pt + (hp - sh) / 2;
canvas.translate(dx, dy);
switch (state) {
case SWITCH_ON:
drawSwitchOn(canvas);
break;
case SWITCH_OFF:
drawSwitchOff(canvas);
break;
case SWITCH_ANIMATION_ON:
drawSwitchOnAnim(canvas);
break;
case SWITCH_ANIMATION_OFF:
drawSwitchOffAnim(canvas);
break;
}
}
private void drawSwitchOn(Canvas canvas) {
float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
drawRoundRect(canvas, switchOnColor, rectAttrs);
float[] ovalAttrs = compOvalAttr(SWITCH_ON_POS);
drawOval(canvas, spotOnColor, ovalAttrs);
drawOvalIn(canvas, spotOnColorIn, ovalAttrs);
drawRoundRectStroke(canvas, DEFAULT_SWITCH_ON_COLOR_OUT);
}
private void drawSwitchOff(Canvas canvas) {
float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
drawRoundRect(canvas, switchOffColor, rectAttrs);
float[] ovalAttrs = compOvalAttr(SWITCH_OFF_POS);
drawOval(canvas, spotOffColor, ovalAttrs);
drawOvalIn(canvas, spotOffColorIn, ovalAttrs);
drawRoundRectStroke(canvas, DEFAULT_SWITCH_OFF_COLOR_OUT);
}
private void drawSwitchOnAnim(Canvas canvas) {
float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
drawRoundRect(canvas, switchOnColor, rectAttrs);
rectAttrs = compRoundRectAttr(currentPos);
drawRoundRect(canvas, switchOffColor, rectAttrs);
float[] ovalShadeOnAttrs = compRoundRectShadeOnAttr(currentPos * 3/2);
float[] ovalAttrs = compOvalAttr(currentPos* 3/2);
int color = compColor(currentPos, DEFAULT_SPOT_OFF_COLOR, DEFAULT_SPOT_ON_COLOR);
int colorIn = compColor(currentPos, DEFAULT_SPOT_OFF_COLOR_IN, DEFAULT_SPOT_ON_COLOR_IN);
drawRoundRect(canvas, color, ovalShadeOnAttrs);
drawOval(canvas, color, ovalAttrs);
drawOvalIn(canvas, colorIn, ovalAttrs);
int strokeColor = compColor(currentPos, DEFAULT_SWITCH_OFF_COLOR_OUT, DEFAULT_SWITCH_ON_COLOR_OUT);
drawRoundRectStroke(canvas, strokeColor);
}
private void drawSwitchOffAnim(Canvas canvas) {
float[] rectAttrs = compRoundRectAttr(SWITCH_OFF_POS);
if (currentPos != 1) {
drawRoundRect(canvas, switchOffColor, rectAttrs);
}
rectAttrs = compRoundRectAttr(1 - currentPos);
drawRoundRect(canvas, switchOffColor, rectAttrs);
float[] ovalAttrs;
if(currentPos > 2.0/3){
ovalAttrs = compOvalAttr(0);
}else{
ovalAttrs = compOvalAttr(1 - currentPos * 3/2);
}
float[] ovalShadeOffAttrs = compRoundRectShadeOffAttr(1 - currentPos * 3/2);
int color = compColor(currentPos, DEFAULT_SPOT_ON_COLOR, DEFAULT_SPOT_OFF_COLOR);
int colorIn = compColor(currentPos, DEFAULT_SPOT_ON_COLOR_IN, DEFAULT_SPOT_OFF_COLOR_IN);
drawRoundRect(canvas, color, ovalShadeOffAttrs);
drawOval(canvas, color, ovalAttrs);
drawOvalIn(canvas, colorIn, ovalAttrs);
int strokeColor = compColor(currentPos, DEFAULT_SWITCH_ON_COLOR_OUT, DEFAULT_SWITCH_OFF_COLOR_OUT);
drawRoundRectStroke(canvas, strokeColor);
}
private void drawRoundRect(Canvas canvas, int color, float[] attrs) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeCap(Paint.Cap.ROUND);
RectF rectF = new RectF();
paint.setColor(color);
rectF.set(attrs[0], attrs[1], attrs[2], attrs[3]);
canvas.drawRoundRect(rectF, attrs[4], attrs[4], paint);
}
private void drawRoundRectStroke(Canvas canvas, int color) {
int sw = dp2px(DEFAULT_WIDTH);
int sh = dp2px(DEFAULT_HEIGHT);
float left = dp2pxFloat((float) 2.4);
float right = sw - left;
float top = dp2pxFloat((float) 2.4);
float bottom = sh - top;
float radius = (bottom - top) * 0.5f;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(color);
paint.setStrokeWidth(dp2pxFloat((float) 3.6));
RectF rectF = new RectF();
rectF.set(left, top, right, bottom);
canvas.drawRoundRect(rectF, radius, radius, paint);
}
private void drawOvalIn(Canvas canvas, int color, float[] attrs) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
int borderWidth = dp2px(DEFAULT_BORDER_WIDTH);
RectF rectFIn = new RectF(attrs[0] + borderWidth, attrs[1] + borderWidth, attrs[2] - borderWidth, attrs[3] - borderWidth);
canvas.drawOval(rectFIn, paint);
}
private void drawOval(Canvas canvas, int color, float[] attrs) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
RectF rectF = new RectF(attrs[0], attrs[1], attrs[2], attrs[3]);
canvas.drawOval(rectF, paint);
}
private float[] compRoundRectAttr(float pos) {
int sw = dp2px(DEFAULT_WIDTH);
int sh = dp2px(DEFAULT_HEIGHT);
float left = sw * pos;
float right = sw - left;
float top = sh * pos;
float bottom = sh - top;
float radius = (bottom - top) * 0.5f;
return new float[]{left, top, right, bottom, radius};
}
private float[] compRoundRectShadeOnAttr(float pos) {
int sw = dp2px(DEFAULT_WIDTH);
int sh = dp2px(DEFAULT_HEIGHT);
int oh = sh - 2 * spotPadding;
float left, right, top, bottom;
if(pos < 0.35){
left = 0;
right = spotPadding + (sw - sh) * pos + oh;
top = spotPadding;
bottom = oh + top;
}else{
left = spotPadding + (sw - sh) * pos *2/3;
right = spotPadding + (sw - sh) * pos *2/3+ oh;
top = spotPadding;
bottom = oh + top;
}
float radius = (bottom - top) * 0.5f;
return new float[]{left, top, right, bottom, radius};
}
private float[] compRoundRectShadeOffAttr(float pos) {
int sw = dp2px(DEFAULT_WIDTH);
int sh = dp2px(DEFAULT_HEIGHT);
int oh = sh - 2 * spotPadding;
float left, right, top, bottom;
if(pos > 0.65){
left = spotPadding + (sw - sh) * pos;
right = sw - spotPadding;
top = spotPadding;
bottom = oh + top;
}else{
left = spotPadding + (sw - sh) * (2*pos + 1)/3;
right = spotPadding + (sw - sh) * (2*pos + 1)/3 + oh;
top = spotPadding;
bottom = oh + top;
}
float radius = (bottom - top) * 0.5f;
return new float[]{left, top, right, bottom, radius};
}
private float[] compOvalAttr(float pos) {
if(pos > 1){
pos = 1;
}
int sw = dp2px(DEFAULT_WIDTH);
int sh = dp2px(DEFAULT_HEIGHT);
int oh = sh - 2 * spotPadding;
float left = spotPadding + (sw - sh) * pos;
float right = left + oh;
float top = spotPadding;
float bottom = oh + top;
return new float[]{left, top, right, bottom};
}
private int compColor(float fraction, int startColor, int endColor) {
return (Integer) new ArgbEvaluator().evaluate(fraction, startColor, endColor);
}
#Override
public boolean performClick() {
toggle();
final boolean handled = super.performClick();
if (!handled) {
// View only makes a sound effect if the onClickListener was
// called, so we'll need to make one here instead.
playSoundEffect(SoundEffectConstants.CLICK);
}
return handled;
}
public int dp2px(float dpValue) {
float scale = getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public float dp2pxFloat(float dpValue) {
float scale = getResources().getDisplayMetrics().density;
return dpValue * scale + 0.5f;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void setChecked(boolean checked) {
if (isMoving) {
return;
}
if (mChecked != checked) {
mChecked = checked;
// Avoid infinite recursions if setChecked() is called from a listener
if (mBroadcasting) {
return;
}
mBroadcasting = true;
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, mChecked);
}
mBroadcasting = false;
if (mChecked) {
state = State.SWITCH_ANIMATION_ON;
} else {
state = State.SWITCH_ANIMATION_OFF;
}
if (isAttachedToWindow() && isLaidOut()) {
animateToCheckedState();
} else {
// Immediately move the thumb to the new position.
cancelPositionAnimator();
currentPos = 0;
}
}
}
private void cancelPositionAnimator() {
if (valueAnimator != null) {
valueAnimator.cancel();
}
}
private void animateToCheckedState() {
valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(duration);
valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
currentPos = (float) animation.getAnimatedValue();
invalidate();
}
});
valueAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
isMoving = true;
}
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
isMoving = false;
}
});
if (!valueAnimator.isRunning()) {
valueAnimator.start();
currentPos = 0;
}
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
#Override
public boolean isChecked() {
return mChecked;
}
#Override
public void toggle() {
setChecked(!mChecked);
}
public int getSwitchOnColor() {
return switchOnColor;
}
public void setSwitchOnColor(#ColorInt int switchOnColor) {
this.switchOnColor = switchOnColor;
invalidate();
}
public int getSwitchOffColor() {
return switchOffColor;
}
public void setSwitchOffColor(#ColorInt int switchOffColor) {
this.switchOffColor = switchOffColor;
invalidate();
}
public int getSpotOnColor() {
return spotOnColor;
}
public void setSpotOnColor(#ColorInt int spotOnColor) {
this.spotOnColor = spotOnColor;
invalidate();
}
public int getSpotOffColor() {
return spotOffColor;
}
public void setSpotOffColor(#ColorInt int spotOffColor) {
this.spotOffColor = spotOffColor;
invalidate();
}
public int getSpotPadding() {
return spotPadding;
}
public void setSpotPadding(int spotPadding) {
this.spotPadding = spotPadding;
invalidate();
}
public int getSwitchOffStrokeColor() {
return switchOffStrokeColor;
}
public void setSwitchOffStrokeColor(int switchOffStrokeColor) {
this.switchOffStrokeColor = switchOffStrokeColor;
invalidate();
}
public int getSwitchOnStrokeColor() {
return switchOnStrokeColor;
}
public void setSwitchOnStrokeColor(int switchOnStrokeColor) {
this.switchOnStrokeColor = switchOnStrokeColor;
invalidate();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public interface OnCheckedChangeListener {
/**
* Called when the checked state of a switch has changed.
*
* #param s The switch whose state has changed.
* #param isChecked The new checked state of switch.
*/
void onCheckedChanged(MySwitchButton s, boolean isChecked);
}
}
You need to set value in preferences when the switch state is changed,
switchButton.setOnCheckedChangeListener(new MySwitchButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(MySwitchButton s, boolean isChecked) {
setPreference(context,ischecked);
//your code
}
});
EDIT:
In your oncreate() method, use
switchButton.setChecked(getPreference());
And directly return value in getPreference() method as,
public boolean getPreference() {
SharedPreferences settings = this.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
// Toast.makeText(this,"EMP ID is "+emp_id,Toast.LENGTH_LONG).show();
Common.punchedIn = settings.getBoolean("punch", false);
Toast.makeText(this,"PUNCH IN STATUS "+String.valueOf(Common.punchedIn),Toast.LENGTH_LONG).show();
return Common.punchedIn;
}
Replace your onCreate code with this, after retrieve the shared-preference data:
switchButton.post(new Runnable() {
#Override
public void run() {
if(Common.punchedIn) {
switchButton.setChecked(false);
}
else {
switchButton.setChecked(true);
}
}
});
For all those facing similar issues this is how I did it
There are static int variables in MySwitchButton class and I just swapped the position.Its now working fine
getPreference();
if (Common.punchedIn) {
switchButton.setOnCheckedChangeListener(null);
//switchButton.setChecked(false);
punchStatus_text.setText("Punch Out");
MySwitchButton.SWITCH_OFF_POS=1;
MySwitchButton.SWITCH_ON_POS=0;
//setColorPreference(AttendanceActivity.this,Color.GREEN,Color.RED);
} else {
switchButton.setOnCheckedChangeListener(null);
//switchButton.setChecked(true);
punchStatus_text.setText("Punch In");
MySwitchButton.SWITCH_OFF_POS=0;
MySwitchButton.SWITCH_ON_POS=1;
//setColorPreference(AttendanceActivity.this,Color.RED,Color.GREEN);
}
Try using handlers that check value after some interval and accordingly change the state of the switch automatically to checked or unchecked.
new Handler().postDelayed(new Runnable()
{ public void run()
{ runOnUiThread(new Runnable()
{ public void run() {
if(check) {
aSwitch.setChecked(true);
}
else {
aSwitch.setChecked(false);
}
} }); } }, 5000);
I use a Custom Calendar View using
Viewpager - FragmentStateAdapter - Fragment - Viewgroup -view
I can get first fragment and second fragment when I swipe page, but third fragment doesn't show anything. so I debug and get draw() method doesn't call on View class.
I use Invalidate(), setWillNotDraw(false) but it doesn't work.
I saw in the log that fragment cycle operates fine. I don't know what the problem is.
Here is my code:
FragmentActivity
public class FindClassFragmentActivity extends FragmentActivity {
private static final int COUNT_PAGE = 12;
ViewPager mViewPager;
CalendarFragmentStatePagerAdapter calendarAdapter;
ImageButton previous;
ImageButton next;
TextView presentMonth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.findclass_main_layout);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
previous = (ImageButton) findViewById(R.id.previous_month);
next = (ImageButton) findViewById(R.id.next_month);
presentMonth = (TextView) findViewById(R.id.present_month);
calendarAdapter = new CalendarFragmentStatePagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(calendarAdapter);
// mViewPager.setOffscreenPageLimit(24);
}
public void PrevOrNext(View v) {
switch (v.getId()) {
case R.id.previous_month :
break;
case R.id.next_month :
break;
}
}
}
FragmentStatePagerAdapter
public class CalendarFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
private HashMap<Integer, MonthFragment> monthMap;
private int numOfMonth;
public CalendarFragmentStatePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 24;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Log.e("solme6", "instantiateItem : " + position );
return super.instantiateItem(container, position);
}
#Override
public Fragment getItem(int position) {
return MonthFragment.newInstance(position);
}
}
CalendarMonthView
public class CalendarMonthView extends ViewGroup {
private final int mScreenWidth;
private final int mWidthDate;
private int mDateOfWeek; // 1일의 요일
private int mDefaultTextSize = 40;
private int mTextColor = Color.BLUE;
public static String[] DAY_OF_WEEK = null;
public CalendarMonthView(Context context, AttributeSet attrs) {
super(context, attrs);
mScreenWidth = getResources().getDisplayMetrics().widthPixels;
mWidthDate = mScreenWidth / 7;
DAY_OF_WEEK = getResources().getStringArray(R.array.day_of_week);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
Log.e("solme",Integer.toString(count));
int maxHeight = 0;
int childState = 0;
int childViewFullWidth = 0;
int childViewFullheight = 0;
for(int i=0; i < count; i++) {
final View child = getChildAt(i);
getChildAt(i).setWillNotDraw(false);
if (child.getVisibility() == GONE) {
continue;
}
childViewFullWidth = child.getMeasuredWidth();
childViewFullheight = child.getMeasuredHeight();
measureChild(child, widthMeasureSpec, heightMeasureSpec); // 자식의 크기 측정.
childState = combineMeasuredStates(childState, child.getMeasuredState());
}
setMeasuredDimension(childViewFullWidth, childViewFullheight);
LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
params.height = maxHeight;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int curLeft = 0; // 왼쪽 스타트 지점 값.
int curTop = 0;
int eachCellWidth, eachCellHeight;
int curDayHeight;
final int childWidth = this.getMeasuredWidth(); // 1440
final int childHeight = this.getMeasuredHeight(); //2355
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE)
return;
child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
eachCellWidth = mWidthDate;
curDayHeight = 100;
eachCellHeight = (getMeasuredHeight() - curDayHeight) / 6;
if (i < 7) {
child.layout(curLeft, curTop, curLeft + eachCellWidth, curTop + curDayHeight);
curLeft += eachCellWidth;
if (curLeft + eachCellWidth >= childWidth) {
curLeft = 0;
curTop += curDayHeight;
}
} else {
if (i == 7) {
curLeft = (mDateOfWeek - 1) * eachCellWidth;
}
child.layout(curLeft, curTop, curLeft + eachCellWidth, curTop + eachCellHeight);
curLeft += eachCellWidth;
if (curLeft + eachCellWidth >= childWidth) {
curLeft = 0;
curTop += eachCellHeight;
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
Log.e("solme6", "CalendarMonthView : onDraw");
super.onDraw(canvas);
}
#Override
public void draw(Canvas canvas) {
Log.e("solme6", "CalendarMonthView : draw");
super.draw(canvas);
}
#Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
}
private Paint makePaint(int color) {
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(color);
p.setTextSize(mDefaultTextSize);
return p;
}
public void initCalendar(int dayOfWeek, int maxDateOfMonth) {
mDateOfWeek = dayOfWeek;
}
}
CalendarcellView
public class CalendarCellView extends View {
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintTextWhite = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackground = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackgroundToday = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint mPaintBackgroundEvent = new Paint(Paint.ANTI_ALIAS_FLAG);
private int dayOfWeek = -1;
private boolean isStaticText = false;
private long millis;
private Rect rect;
private boolean isTouchMode;
private int dp11;
private int dp16;
private boolean hasEvent = false;
private int[] mColorEvents;
private final float RADIUS = 100f;
public CalendarCellView(Context context) {
super(context);
initialize(context);
Log.e("solme6", "CalendarCellView : constructor");
}
public CalendarCellView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
private void initialize(Context context) {
dp11 = (int) dp2px(getContext(), 11);
dp16 = (int) dp2px(getContext(), 16);
mPaint.setColor(Color.BLACK);
mPaint.setTextSize(dp11);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaintTextWhite.setColor(Color.WHITE);
mPaintTextWhite.setTextSize(dp11);
mPaintTextWhite.setTextAlign(Paint.Align.CENTER);
mPaintBackground.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
mPaintBackgroundToday.setColor(ContextCompat.getColor(getContext(), R.color.today));
mPaintBackgroundEvent.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
setPadding(30, 0, 30, 0);
}
public float dp2px(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.e("solme6","CalendarCellView : onMeasure");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Log.e("solme6", "CalendarCellView : onLayout");
super.onLayout(changed, left, top, right, bottom);
}
#Override
protected void dispatchDraw(Canvas canvas) {
Log.e("solme6", "CalendarCellView : dispatchDraw");
}
#Override
public void draw(Canvas canvas) {
Log.e("solme6", "CalendarCellView : draw");
super.draw(canvas);
}
#Override
protected void onDraw(Canvas canvas) {
Log.e("solme6", "CalendarCellView : onDraw");
super.onDraw(canvas);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((mPaint.descent() + mPaint.ascent()) / 2));
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
set
CalendarMonthView calendarView = (CalendarMonthView) getParent();
if (calendarView.getParent() instanceof ViewPager) {
ViewGroup parent = (ViewPager) calendarView.getParent();
CalendarCellView tagView = (CalendarCellView) parent.getTag();
if (!isStaticText && tagView != null && tagView.getTag() != null && tagView.getTag() instanceof Long) {
long millis = (long) tagView.getTag();
if (isSameDay(millis, this.millis)) {
// RectF rectF = new RectF(xPos - dp16, getHeight() / 2 - dp16, xPos + dp16, getHeight() / 2 + dp16);
// canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackground);
}
}
}
if (!isStaticText && isToday(millis)) {
RectF rectF = new RectF(xPos - dp16, getHeight() / 2 - dp16, xPos + dp16, getHeight() / 2 + dp16);
canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackgroundToday);
}
if (isStaticText) {
// 요일 표시
canvas.drawText(CalendarMonthView.DAY_OF_WEEK[dayOfWeek], xPos, yPos, mPaint);
} else {
// 날짜 표시
if (isToday(millis)) {
canvas.drawText(calendar.get(Calendar.DATE) + "", xPos, yPos, mPaintTextWhite);
} else {
canvas.drawText(calendar.get(Calendar.DATE) + "", xPos, yPos, mPaint);
}
}
if (hasEvent) {
mPaintBackgroundEvent.setColor(getResources().getColor(mColorEvents[0]));
RectF rectF = new RectF(xPos - 5, getHeight() / 2 + 20, xPos + 5, getHeight() / 2 + 30);
canvas.drawRoundRect(rectF, RADIUS, RADIUS, mPaintBackgroundToday);
}
}
private boolean isToday(long millis) {
Calendar cal1 = Calendar.getInstance();
return isSameDay(cal1.getTimeInMillis(), millis);
}
public void setDate(long millis) {
this.millis = millis;
setTag(millis);
}
public void setDayOfWeek(int dayOfWeek) {
this.dayOfWeek = dayOfWeek;
isStaticText = true;
}
public void setEvent(int... resid) {
hasEvent = true;
mColorEvents = resid;
}
public boolean isSameDay(long millis1, long millis2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTimeInMillis(millis1);
cal2.setTimeInMillis(millis2);
Log.d("hatti.calendar", "" + cal1.get(Calendar.YEAR) + "" + cal1.get(Calendar.MONTH) + "" + cal1.get(Calendar.DATE) + " VS " +
cal2.get(Calendar.YEAR) + "" + cal2.get(Calendar.MONTH) + "" + cal2.get(Calendar.DATE));
return (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DATE) == cal2.get(Calendar.DATE));
}
public boolean isStaticText() {
return isStaticText;
}
}
Is there anything I should do for add Fragment on Adapter?
in your pager adapter,
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
how can i delete this black part and description from daimajia.slider
or is there other alternative for using a slider only with bullet on it.
Yes, you can make a slide show with just bullets and no text.
Use ViewPager to make the slides
Screen slides are transitions between one entire screen to another and
are common with UIs like setup wizards or slideshows. This lesson
shows you how to do screen slides with a ViewPager provided by the
support library. ViewPagers can animate screen slides automatically.
for adding the dots, use ViewPagerIndicator library by Jake Wharton and use the CirclePageIndicator provided by it. Done!
You can use viewpager with below class.
CirclePageIndicator.java
public class CirclePageIndicator extends View implements PageIndicator {
private static final int INVALID_POINTER = -1;
private float mRadius;
private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG);
private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mListener;
private int mCurrentPage;
private int mSnapPage;
private float mPageOffset;
private int mScrollState;
private int mOrientation;
private boolean mCentered;
private boolean mSnap;
private int mTouchSlop;
private float mLastMotionX = -1;
private int mActivePointerId = INVALID_POINTER;
private boolean mIsDragging;
public CirclePageIndicator(Context context) {
this(context, null);
}
public CirclePageIndicator(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);
}
public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode()) return;
//Load defaults from resources
final Resources res = getResources();
final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
//default_circle_indicator_fill_color
final int defaultFillColor = res.getColor(R.color.holo_blue_dark);
final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
final int defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color);
final float defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width);
final float defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius);
final boolean defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered);
final boolean defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap);
//Retrieve styles attributes
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0);
mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered);
mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation);
mPaintPageFill.setStyle(Style.FILL);
mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));
mPaintStroke.setStyle(Style.STROKE);
mPaintStroke.setColor(a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor));
mPaintStroke.setStrokeWidth(a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth));
mPaintFill.setStyle(Style.FILL);
mPaintFill.setColor(a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor));
mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius);
mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap);
Drawable background = a.getDrawable(R.styleable.CirclePageIndicator_android_background);
if (background != null) {
setBackgroundDrawable(background);
}
a.recycle();
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
}
public void setCentered(boolean centered) {
mCentered = centered;
invalidate();
}
public boolean isCentered() {
return mCentered;
}
public void setPageColor(int pageColor) {
mPaintPageFill.setColor(pageColor);
invalidate();
}
public int getPageColor() {
return mPaintPageFill.getColor();
}
public void setFillColor(int fillColor) {
mPaintFill.setColor(fillColor);
invalidate();
}
public int getFillColor() {
return mPaintFill.getColor();
}
public void setOrientation(int orientation) {
switch (orientation) {
case HORIZONTAL:
case VERTICAL:
mOrientation = orientation;
requestLayout();
break;
default:
throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
}
}
public int getOrientation() {
return mOrientation;
}
public void setStrokeColor(int strokeColor) {
mPaintStroke.setColor(strokeColor);
invalidate();
}
public int getStrokeColor() {
return mPaintStroke.getColor();
}
public void setStrokeWidth(float strokeWidth) {
mPaintStroke.setStrokeWidth(strokeWidth);
invalidate();
}
public float getStrokeWidth() {
return mPaintStroke.getStrokeWidth();
}
public void setRadius(float radius) {
mRadius = radius;
invalidate();
}
public float getRadius() {
return mRadius;
}
public void setSnap(boolean snap) {
mSnap = snap;
invalidate();
}
public boolean isSnap() {
return mSnap;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mViewPager == null) {
return;
}
final int count = mViewPager.getAdapter().getCount();
if (count == 0) {
return;
}
if (mCurrentPage >= count) {
setCurrentItem(count - 1);
return;
}
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
if (mOrientation == HORIZONTAL) {
longSize = getWidth();
longPaddingBefore = getPaddingLeft();
longPaddingAfter = getPaddingRight();
shortPaddingBefore = getPaddingTop();
} else {
longSize = getHeight();
longPaddingBefore = getPaddingTop();
longPaddingAfter = getPaddingBottom();
shortPaddingBefore = getPaddingLeft();
}
final float threeRadius = mRadius * 3;
final float shortOffset = shortPaddingBefore + mRadius;
float longOffset = longPaddingBefore + mRadius;
if (mCentered) {
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
}
float dX;
float dY;
float pageFillRadius = mRadius;
if (mPaintStroke.getStrokeWidth() > 0) {
pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
}
//Draw stroked circles
for (int iLoop = 0; iLoop < count; iLoop++) {
float drawLong = longOffset + (iLoop * threeRadius);
if (mOrientation == HORIZONTAL) {
dX = drawLong;
dY = shortOffset;
} else {
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (mPaintPageFill.getAlpha() > 0) {
canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != mRadius) {
canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
}
}
//Draw the filled circle according to the current scroll
float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
if (!mSnap) {
cx += mPageOffset * threeRadius;
}
if (mOrientation == HORIZONTAL) {
dX = longOffset + cx;
dY = shortOffset;
} else {
dX = shortOffset;
dY = longOffset + cx;
}
canvas.drawCircle(dX, dY, mRadius, mPaintFill);
}
public boolean onTouchEvent(android.view.MotionEvent ev) {
if (super.onTouchEvent(ev)) {
return true;
}
if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
return false;
}
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mLastMotionX = ev.getX();
break;
case MotionEvent.ACTION_MOVE: {
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = x - mLastMotionX;
if (!mIsDragging) {
if (Math.abs(deltaX) > mTouchSlop) {
mIsDragging = true;
}
}
if (mIsDragging) {
mLastMotionX = x;
if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
mViewPager.fakeDragBy(deltaX);
}
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!mIsDragging) {
final int count = mViewPager.getAdapter().getCount();
final int width = getWidth();
final float halfWidth = width / 2f;
final float sixthWidth = width / 6f;
if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager.setCurrentItem(mCurrentPage - 1);
}
return true;
} else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager.setCurrentItem(mCurrentPage + 1);
}
return true;
}
}
mIsDragging = false;
mActivePointerId = INVALID_POINTER;
if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mLastMotionX = MotionEventCompat.getX(ev, index);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
return true;
}
#Override
public void setViewPager(ViewPager view) {
if (mViewPager == view) {
return;
}
if (mViewPager != null) {
mViewPager.setOnPageChangeListener(null);
}
if (view.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
mViewPager = view;
mViewPager.setOnPageChangeListener(this);
invalidate();
}
#Override
public void setViewPager(ViewPager view, int initialPosition) {
setViewPager(view);
setCurrentItem(initialPosition);
}
#Override
public void setCurrentItem(int item) {
if (mViewPager == null) {
throw new IllegalStateException("ViewPager has not been bound.");
}
mViewPager.setCurrentItem(item);
mCurrentPage = item;
invalidate();
}
#Override
public void notifyDataSetChanged() {
invalidate();
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mCurrentPage = position;
mPageOffset = positionOffset;
invalidate();
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageSelected(int position) {
if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position;
mSnapPage = position;
invalidate();
}
if (mListener != null) {
mListener.onPageSelected(position);
}
}
#Override
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mListener = listener;
}
/*
* (non-Javadoc)
*
* #see android.view.View#onMeasure(int, int)
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == HORIZONTAL) {
setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
} else {
setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
}
}
/**
* Determines the width of this view
*
* #param measureSpec
* A measureSpec packed into an int
* #return The width of the view, honoring constraints from measureSpec
*/
private int measureLong(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
//We were told how big to be
result = specSize;
} else {
//Calculate the width according the views count
final int count = mViewPager.getAdapter().getCount();
result = (int)(getPaddingLeft() + getPaddingRight()
+ (count * 2 * mRadius) + (count - 1) * mRadius + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/**
* Determines the height of this view
*
* #param measureSpec
* A measureSpec packed into an int
* #return The height of the view, honoring constraints from measureSpec
*/
private int measureShort(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
//We were told how big to be
result = specSize;
} else {
//Measure the height
result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState)state;
super.onRestoreInstanceState(savedState.getSuperState());
mCurrentPage = savedState.currentPage;
mSnapPage = savedState.currentPage;
requestLayout();
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPage = mCurrentPage;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPage;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPage = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPage);
}
#SuppressWarnings("UnusedDeclaration")
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
Use this class in your xml :
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="fill_parent"
android:layout_height="220dp" />
<com.example.support.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_below="#+id/view_pager"
android:layout_marginTop="10dp" />
i have made a tab view, i want to change the background color of the tabs, but when i set the color on the tab textview background, the strip disappears.
SlidingTabLayout.java
package com.towntrot.checkin;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class SlidingTabLayout extends HorizontalScrollView {
public interface TabColorizer {
int getIndicatorColor(int position);
int getDividerColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setHorizontalScrollBarEnabled(false);
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(android.R.color.white));
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
textView.setAllCaps(true);
}
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
mTabStrip.addView(tabView);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
SlidingTabStrip.java
package com.towntrot.checkin;
import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
class SlidingTabStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 2;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 4;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xffee7600;
private static final int DEFAULT_DIVIDER_THICKNESS_DIPS = 1;
private static final byte DEFAULT_DIVIDER_COLOR_ALPHA = 0x20;
private static final float DEFAULT_DIVIDER_HEIGHT = 0.5f;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
private final Paint mDividerPaint;
private final float mDividerHeight;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
final int themeForegroundColor = getResources().getColor(android.R.color.holo_orange_dark);
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mDefaultTabColorizer.setDividerColors(setColorAlpha(themeForegroundColor,
DEFAULT_DIVIDER_COLOR_ALPHA));
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
mDividerHeight = DEFAULT_DIVIDER_HEIGHT;
mDividerPaint = new Paint();
mDividerPaint.setStrokeWidth((int) (DEFAULT_DIVIDER_THICKNESS_DIPS * density));
}
void onViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final int dividerHeightPx =0;
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
// Vertical separators between the titles
int separatorTop = (height - dividerHeightPx) / 2;
for (int i = 0; i < childCount - 1; i++) {
View child = getChildAt(i);
mDividerPaint.setColor(tabColorizer.getDividerColor(i));
canvas.drawLine(child.getRight(), separatorTop, child.getRight(),
separatorTop + dividerHeightPx, mDividerPaint);
}
}
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
private int[] mIndicatorColors;
private int[] mDividerColors;
#Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
#Override
public final int getDividerColor(int position) {
return mDividerColors[position % mDividerColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
void setDividerColors(int... colors) {
mDividerColors = colors;
}
}
}
In createDefaultTabView i have added:
textView.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
I am new to android, any help is appreciated, Thank you.
When you set background of textview, it covers yours SlidingTabStrip layout (container of tabs), which is below in your view hierarchy, so bottom strips are covered by TextView background.
To change background color of all of tabs, you should add drawing of background to SlidingTabStrip.onDraw method. To change background of all of the tabs, you can e.g. fill whole tabs container using canvas.drawColor(int color) method
#Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final int dividerHeightPx =0;
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
canvas.drawColor(getResources().getColor(android.R.color.holo_orange_dark));
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
// Vertical separators between the titles
int separatorTop = (height - dividerHeightPx) / 2;
for (int i = 0; i < childCount - 1; i++) {
View child = getChildAt(i);
mDividerPaint.setColor(tabColorizer.getDividerColor(i));
canvas.drawLine(child.getRight(), separatorTop, child.getRight(),
separatorTop + dividerHeightPx, mDividerPaint);
}
}
I am used viewpager and also to used custom library CirclePageIndicator and problem is that image draw on select and unselect with space between two circle image draw and but select and unselect image draw and image not draw space between two image, please be help me
Actual ouput i need to and snapshot,
Device output as,
My CirclePageIndicator class as,
public class CirclePageIndicator extends View implements PageIndicator {
private static final int INVALID_POINTER = -1;
private float mRadius;
private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG);
private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mListener;
private int mCurrentPage;
private int mSnapPage;
private float mPageOffset;
private int mScrollState;
private int mOrientation;
private boolean mCentered;
private boolean mSnap;
private int mTouchSlop;
private float mLastMotionX = -1;
private int mActivePointerId = INVALID_POINTER;
private boolean mIsDragging;
public CirclePageIndicator(Context context) {
this(context, null);
}
public CirclePageIndicator(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);
}
#SuppressWarnings("deprecation")
public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode()) return;
//Load defaults from resources
final Resources res = getResources();
final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
final int defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color);
final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
final int defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color);
final float defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width);
final float defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius);
final boolean defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered);
final boolean defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap);
// Retrieve styles attributes
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0);
mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered);
mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation);
mPaintPageFill.setStyle(Style.FILL);
mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));
mPaintStroke.setStyle(Style.STROKE);
mPaintStroke.setColor(a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor));
mPaintStroke.setStrokeWidth(a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth));
mPaintFill.setStyle(Style.FILL);
mPaintFill.setColor(a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor));
mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius);
mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap);
Drawable background = a.getDrawable(R.styleable.CirclePageIndicator_android_background);
if (background != null) {
setBackgroundDrawable(background);
}
a.recycle();
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
}
public void setCentered(boolean centered) {
mCentered = centered;
invalidate();
}
public boolean isCentered() {
return mCentered;
}
public void setPageColor(int pageColor) {
mPaintPageFill.setColor(pageColor);
invalidate();
}
public int getPageColor() {
return mPaintPageFill.getColor();
}
public void setFillColor(int fillColor) {
mPaintFill.setColor(fillColor);
invalidate();
}
public int getFillColor() {
return mPaintFill.getColor();
}
public void setOrientation(int orientation) {
switch (orientation) {
case HORIZONTAL:
case VERTICAL:
mOrientation = orientation;
requestLayout();
break;
default:
throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
}
}
public int getOrientation() {
return mOrientation;
}
public void setStrokeColor(int strokeColor) {
mPaintStroke.setColor(strokeColor);
invalidate();
}
public int getStrokeColor() {
return mPaintStroke.getColor();
}
public void setStrokeWidth(float strokeWidth) {
mPaintStroke.setStrokeWidth(strokeWidth);
invalidate();
}
public float getStrokeWidth() {
return mPaintStroke.getStrokeWidth();
}
public void setRadius(float radius) {
mRadius = radius;
invalidate();
}
public float getRadius() {
return mRadius;
}
public void setSnap(boolean snap) {
mSnap = snap;
invalidate();
}
public boolean isSnap() {
return mSnap;
}
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mViewPager == null) {
return;
}
final int count = mViewPager.getAdapter().getCount();
if (count == 0) {
return;
}
if (mCurrentPage >= count) {
setCurrentItem(count - 1);
return;
}
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
if (mOrientation == HORIZONTAL) {
longSize = getWidth();
longPaddingBefore = getPaddingLeft();
longPaddingAfter = getPaddingRight();
shortPaddingBefore = getPaddingTop();
} else {
longSize = getHeight();
longPaddingBefore = getPaddingTop();
longPaddingAfter = getPaddingBottom();
shortPaddingBefore = getPaddingLeft();
}
final float threeRadius = mRadius * 3;
final float shortOffset = shortPaddingBefore + mRadius;
float longOffset = longPaddingBefore + mRadius;
if (mCentered) {
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
}
float dX = 0.0f;
float dY = 0.0f;
float pageFillRadius = mRadius;
if (mPaintStroke.getStrokeWidth() > 0) {
pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
}
//Draw stroked circles
for (int iLoop = 0; iLoop < count; iLoop++) {
float drawLong = longOffset + (iLoop * threeRadius);
if (mOrientation == HORIZONTAL) {
dX = drawLong;
dY = shortOffset;
} else {
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (mPaintPageFill.getAlpha() > 0) {
canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
// Bitmap mBitmapLine = BitmapFactory.decodeResource(getResources(), R.drawable.slider_line);
// canvas.drawBitmap(mBitmapLine, dX, dY, mPaintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != mRadius) {
// canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
Bitmap mBitmapCircleNormal = BitmapFactory.decodeResource(getResources(), R.drawable.slider_circle_normal);
canvas.drawBitmap(mBitmapCircleNormal, dX, dY, mPaintStroke);
}
}
// Draw the filled circle according to the current scroll
float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
if (!mSnap) {
cx += mPageOffset * threeRadius;
}
if (mOrientation == HORIZONTAL) {
dX = longOffset + cx;
dY = shortOffset;
} else {
dX = shortOffset;
dY = longOffset + cx;
}
// System.out.println("cx === "+cx);
// Bitmap mBitmapLine = BitmapFactory.decodeResource(getResources(), R.drawable.slider_line);
// canvas.drawBitmap(mBitmapLine, dX, dY, mPaintFill);
// canvas.drawCircle(dX, dY, mRadius, mPaintFill);
Bitmap mBitmapCircleHover = BitmapFactory.decodeResource(getResources(), R.drawable.slider_circle_hover);
canvas.drawBitmap(mBitmapCircleHover, dX, dY, mPaintFill);
}
public boolean onTouchEvent(android.view.MotionEvent ev) {
if (super.onTouchEvent(ev)) {
return true;
}
if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
return false;
}
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mLastMotionX = ev.getX();
break;
case MotionEvent.ACTION_MOVE: {
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = x - mLastMotionX;
if (!mIsDragging) {
if (Math.abs(deltaX) > mTouchSlop) {
mIsDragging = true;
}
}
if (mIsDragging) {
mLastMotionX = x;
if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
mViewPager.fakeDragBy(deltaX);
}
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!mIsDragging) {
final int count = mViewPager.getAdapter().getCount();
final int width = getWidth();
final float halfWidth = width / 2f;
final float sixthWidth = width / 6f;
if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager.setCurrentItem(mCurrentPage - 1);
}
return true;
} else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager.setCurrentItem(mCurrentPage + 1);
}
return true;
}
}
mIsDragging = false;
mActivePointerId = INVALID_POINTER;
if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mLastMotionX = MotionEventCompat.getX(ev, index);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
return true;
}
#Override
public void setViewPager(ViewPager view) {
if (mViewPager == view) {
return;
}
if (mViewPager != null) {
mViewPager.setOnPageChangeListener(null);
}
if (view.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
mViewPager = view;
mViewPager.setOnPageChangeListener(this);
invalidate();
}
#Override
public void setViewPager(ViewPager view, int initialPosition) {
setViewPager(view);
setCurrentItem(initialPosition);
}
#Override
public void setCurrentItem(int item) {
if (mViewPager == null) {
throw new IllegalStateException("ViewPager has not been bound.");
}
mViewPager.setCurrentItem(item);
mCurrentPage = item;
invalidate();
}
#Override
public void notifyDataSetChanged() {
invalidate();
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mCurrentPage = position;
mPageOffset = positionOffset;
invalidate();
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageSelected(int position) {
if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position;
mSnapPage = position;
invalidate();
}
if (mListener != null) {
mListener.onPageSelected(position);
}
}
#Override
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mListener = listener;
}
/*
* (non-Javadoc)
*
* #see android.view.View#onMeasure(int, int)
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == HORIZONTAL) {
setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
} else {
setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
}
}
/**
* Determines the width of this view
*
* #param measureSpec
* A measureSpec packed into an int
* #return The width of the view, honoring constraints from measureSpec
*/
private int measureLong(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
//We were told how big to be
result = specSize;
} else {
//Calculate the width according the views count
final int count = mViewPager.getAdapter().getCount();
result = (int)(getPaddingLeft() + getPaddingRight()
+ (count * 2 * mRadius) + (count - 1) * mRadius + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/**
* Determines the height of this view
*
* #param measureSpec
* A measureSpec packed into an int
* #return The height of the view, honoring constraints from measureSpec
*/
private int measureShort(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
//We were told how big to be
result = specSize;
} else {
//Measure the height
result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState)state;
super.onRestoreInstanceState(savedState.getSuperState());
mCurrentPage = savedState.currentPage;
mSnapPage = savedState.currentPage;
requestLayout();
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPage = mCurrentPage;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPage;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPage = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPage);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}