Customising Layout for Google's SlidingTabStrip library - java

So Google includes the SlidingTabStrip as an open source library in the Android Studio sample collection:
class SlidingTabStrip 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 = 3;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
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 = outValue.data;
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
void setSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
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 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);
}
/**
* Set the alpha value of the {#code color} to be the given {#code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {#code color1} and {#code color2} using the given ratio.
*
* #param ratio of which to blend. 1.0 will return {#code color1}, 0.5 will give an even blend,
* 0.0 will return {#code color2}.
*/
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;
#Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
}
With its layout file:
<com.example.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000" />
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
I'm just unable to find out how I can completely customise the layout of this library such as border thickness, color or other properties which corresponds to these constants in the library such as SELECTED_INDICATOR_THICKNESS_DIPS and DEFAULT_SELECTED_INDICATOR_COLOR, if I assign a theme in the layout file I can only change common properties like background and foreground color but not border thickness or other properties only available for the SlidingTabStrip properties
Any idea how to change these without modifying the actual library code?
The library is located here:
https://developer.android.com/samples/SlidingTabsBasic/src/com.example.android.common/view/SlidingTabStrip.html

You can change border thickness, color or other properties in the class itself:
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 = 8;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
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;
according to your requirement.
The color codes are in hex format.
For example(how to change the indicator color):
class SlidingTabStrip extends LinearLayout {
// change the strip color
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
...
}
Check Sliding Tab Layout

Related

Custom view being drawn sometimes

I have a custom view, that is sometimes being drawn and sometimes not .. this is reproduce-able across multiple phone.
Don't know why this is happening .. setDimensions() is being called during the onMeasure call of a GalleryGridElement (relative layout) which I use as gallery elements in my recyclerview.
One example would be .. going into the recycler view gallery activity, the circular progress view is there .. when you leave the activity and come back .. onResume creates a new adapter and gives it to the recycler view .. however the circular progress views don't show this time:
public class CircularProgressView extends View {
private Paint mIndicatorColour;
private RectF mIndicatorRect;
private Paint mBackCircleColour;
private static final float START_ANGLE = -90;
private volatile float mStopAngle = 0;
private float mOutterCircleStrokeWidth = 20;
private float mInnerCircleStrokeWidth = 16;
private float mViewWidth = 0, mViewHeight = 0;
private volatile int mCurrentProgress = 0;
private ExecutorService mExecutorService;
public CircularProgressView(Context context) {
super(context);
setUp();
}
public CircularProgressView(Context context, AttributeSet attrs) {
super(context, attrs);
setUp();
}
public CircularProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setUp();
}
private void setUp(){
mIndicatorRect = new RectF(0,0,300,300);
mIndicatorColour = new Paint();
mIndicatorColour.setColor(Color.parseColor("#D62F85"));
mIndicatorColour.setStyle(Paint.Style.STROKE);
mIndicatorColour.setStrokeWidth(mInnerCircleStrokeWidth);
mIndicatorColour.setAntiAlias(true);
mIndicatorColour.setDither(true);
mIndicatorColour.setStrokeJoin(Paint.Join.ROUND);
mIndicatorColour.setStrokeCap(Paint.Cap.ROUND);
mBackCircleColour = new Paint();
mBackCircleColour.setColor(Color.WHITE);
mBackCircleColour.setStyle(Paint.Style.STROKE);
mBackCircleColour.setStrokeWidth(mOutterCircleStrokeWidth);
mBackCircleColour.setAntiAlias(true);
mBackCircleColour.setDither(true);
mBackCircleColour.setStrokeJoin(Paint.Join.ROUND);
mBackCircleColour.setStrokeCap(Paint.Cap.ROUND);
mExecutorService = Executors.newSingleThreadExecutor();
}
public void setDimensions(float width, int scaleCircleThicknessValue){
mViewHeight = width;
mViewWidth = width;
mIndicatorRect.left = mIndicatorRect.top = mOutterCircleStrokeWidth;
mIndicatorRect.right = mIndicatorRect.bottom = width - mOutterCircleStrokeWidth;
mIndicatorColour.setStrokeWidth(mInnerCircleStrokeWidth);
mBackCircleColour.setStrokeWidth(mOutterCircleStrokeWidth);
mInnerCircleStrokeWidth = (0.1f * scaleCircleThicknessValue) * width;
mOutterCircleStrokeWidth = mInnerCircleStrokeWidth + 5;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int desiredWidth = Math.round(mViewWidth);
int desiredHeight = Math.round(mViewHeight);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//Set values
setMeasuredDimension(width, height);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawArc(mIndicatorRect, 0, 360, false, mBackCircleColour);
canvas.drawArc(mIndicatorRect, START_ANGLE, mStopAngle, false, mIndicatorColour);
}
public synchronized void setProgress(final int progress) {
if ((mCurrentProgress != progress) && (progress > 0)) {
mCurrentProgress = progress;
mExecutorService.submit(new Runnable() {
#Override
public void run() {
final float currentAngle = mStopAngle;
float newAngle = (360f * ((float) progress / 100f));
float step = (Math.round(newAngle) - Math.round(currentAngle)) <= 1 ? 1 : (newAngle - currentAngle)/5f;
if (step < 0.01) {
newAngle = 359;
}
for (float i = currentAngle; i < newAngle; i += step) {
try {
mStopAngle = i;
postInvalidate();
Thread.sleep(1000 / 60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
public float getProgress(){
return (360f-mStopAngle) < 1f ? 1 : mStopAngle / 360f;
}
}
Just following up on this incase someone runs into this issue:
Since I am using a custom view inside a custom view with the recycler view.
When I bind the view-holder to model, I make sure to completely re-render the view ... ie :
mCircularProgressView.setVisibility(VISIBLE);
mCircularProgressView.setDimensions(getWidth() * 0.82f, 1);
mCircularProgressView.requestLayout();
mCircularProgressView.postInvalidate();
This makes sure the view is drawn no matter what.

Change Radius of arc

I am using this Github Library https://github.com/lzyzsd/CircleProgress.
But i am not getting how to increse size of arc or chane its circumference means its starting and ending point .
I am unable to it ,please help in it .
Here is my xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:background="#4a4a4a" xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Player Header -->
<!-- Progress Bar/Seek bar -->
<com.androidhive.musicplayer.equalizer.ArcProgress
android:id="#+id/songProgressBar"
android:background="#214193"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:arc_progress="55"
custom:arc_bottom_text="MEMORY"/>
</RelativeLayout>
Here is ArcProgress.java
package com.androidhive.musicplayer.equalizer;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import com.androidhive.musicplayer.R;
/**
* Created by bruce on 11/6/14.
*/
public class ArcProgress extends View {
private Paint paint;
protected Paint textPaint;
private RectF rectF = new RectF();
private float strokeWidth;
private float suffixTextSize;
private float bottomTextSize;
private String bottomText;
private float textSize;
private int textColor;
private int progress = 0;
private int max;
private int finishedStrokeColor;
private int unfinishedStrokeColor;
private float arcAngle;
private String suffixText = "%";
private float suffixTextPadding;
private float arcBottomHeight;
private final int default_finished_color = Color.WHITE;
private final int default_unfinished_color = Color.rgb(72, 106, 176);
private final int default_text_color = Color.rgb(66, 145, 241);
private final float default_suffix_text_size;
private final float default_suffix_padding;
private final float default_bottom_text_size;
private final float default_stroke_width;
private final String default_suffix_text;
private final int default_max = 100;
private final float default_arc_angle = 360 * 0.8f;
private float default_text_size;
private final int min_size;
private static final String INSTANCE_STATE = "saved_instance";
private static final String INSTANCE_STROKE_WIDTH = "stroke_width";
private static final String INSTANCE_SUFFIX_TEXT_SIZE = "suffix_text_size";
private static final String INSTANCE_SUFFIX_TEXT_PADDING = "suffix_text_padding";
private static final String INSTANCE_BOTTOM_TEXT_SIZE = "bottom_text_size";
private static final String INSTANCE_BOTTOM_TEXT = "bottom_text";
private static final String INSTANCE_TEXT_SIZE = "text_size";
private static final String INSTANCE_TEXT_COLOR = "text_color";
private static final String INSTANCE_PROGRESS = "progress";
private static final String INSTANCE_MAX = "max";
private static final String INSTANCE_FINISHED_STROKE_COLOR = "finished_stroke_color";
private static final String INSTANCE_UNFINISHED_STROKE_COLOR = "unfinished_stroke_color";
private static final String INSTANCE_ARC_ANGLE = "arc_angle";
private static final String INSTANCE_SUFFIX = "suffix";
public ArcProgress(Context context) {
this(context, null);
}
public ArcProgress(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ArcProgress(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
default_text_size = Utils.sp2px(getResources(), 18);
min_size = (int) Utils.dp2px(getResources(), 100);
default_text_size = Utils.sp2px(getResources(), 40);
default_suffix_text_size = Utils.sp2px(getResources(), 15);
default_suffix_padding = Utils.dp2px(getResources(), 4);
default_suffix_text = "%";
default_bottom_text_size = Utils.sp2px(getResources(), 10);
default_stroke_width = Utils.dp2px(getResources(), 4);
TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ArcProgress, defStyleAttr, 0);
initByAttributes(attributes);
attributes.recycle();
initPainters();
}
protected void initByAttributes(TypedArray attributes) {
finishedStrokeColor = attributes.getColor(R.styleable.ArcProgress_arc_finished_color, default_finished_color);
unfinishedStrokeColor = attributes.getColor(R.styleable.ArcProgress_arc_unfinished_color, default_unfinished_color);
textColor = attributes.getColor(R.styleable.ArcProgress_arc_text_color, default_text_color);
textSize = attributes.getDimension(R.styleable.ArcProgress_arc_text_size, default_text_size);
arcAngle = attributes.getFloat(R.styleable.ArcProgress_arc_angle, default_arc_angle);
setMax(attributes.getInt(R.styleable.ArcProgress_arc_max, default_max));
setProgress(attributes.getInt(R.styleable.ArcProgress_arc_progress, 0));
strokeWidth = attributes.getDimension(R.styleable.ArcProgress_arc_stroke_width, default_stroke_width);
suffixTextSize = attributes.getDimension(R.styleable.ArcProgress_arc_suffix_text_size, default_suffix_text_size);
suffixText = TextUtils.isEmpty(attributes.getString(R.styleable.ArcProgress_arc_suffix_text)) ? default_suffix_text : attributes.getString(R.styleable.ArcProgress_arc_suffix_text);
suffixTextPadding = attributes.getDimension(R.styleable.ArcProgress_arc_suffix_text_padding, default_suffix_padding);
bottomTextSize = attributes.getDimension(R.styleable.ArcProgress_arc_bottom_text_size, default_bottom_text_size);
bottomText = attributes.getString(R.styleable.ArcProgress_arc_bottom_text);
}
protected void initPainters() {
textPaint = new TextPaint();
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
textPaint.setAntiAlias(true);
paint = new Paint();
paint.setColor(default_unfinished_color);
paint.setAntiAlias(true);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
public void invalidate() {
initPainters();
super.invalidate();
}
public float getStrokeWidth() {
return strokeWidth;
}
public void setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
this.invalidate();
}
public float getSuffixTextSize() {
return suffixTextSize;
}
public void setSuffixTextSize(float suffixTextSize) {
this.suffixTextSize = suffixTextSize;
this.invalidate();
}
public String getBottomText() {
return bottomText;
}
public void setBottomText(String bottomText) {
this.bottomText = bottomText;
this.invalidate();
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
if (this.progress > getMax()) {
this.progress %= getMax();
}
invalidate();
}
public int getMax() {
return max;
}
public void setMax(int max) {
if (max > 0) {
this.max = max;
invalidate();
}
}
public float getBottomTextSize() {
return bottomTextSize;
}
public void setBottomTextSize(float bottomTextSize) {
this.bottomTextSize = bottomTextSize;
this.invalidate();
}
public float getTextSize() {
return textSize;
}
public void setTextSize(float textSize) {
this.textSize = textSize;
this.invalidate();
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
this.invalidate();
}
public int getFinishedStrokeColor() {
return finishedStrokeColor;
}
public void setFinishedStrokeColor(int finishedStrokeColor) {
this.finishedStrokeColor = finishedStrokeColor;
this.invalidate();
}
public int getUnfinishedStrokeColor() {
return unfinishedStrokeColor;
}
public void setUnfinishedStrokeColor(int unfinishedStrokeColor) {
this.unfinishedStrokeColor = unfinishedStrokeColor;
this.invalidate();
}
public float getArcAngle() {
return arcAngle;
}
public void setArcAngle(float arcAngle) {
this.arcAngle = arcAngle;
this.invalidate();
}
public String getSuffixText() {
return suffixText;
}
public void setSuffixText(String suffixText) {
this.suffixText = suffixText;
this.invalidate();
}
public float getSuffixTextPadding() {
return suffixTextPadding;
}
public void setSuffixTextPadding(float suffixTextPadding) {
this.suffixTextPadding = suffixTextPadding;
this.invalidate();
}
#Override
protected int getSuggestedMinimumHeight() {
return min_size;
}
#Override
protected int getSuggestedMinimumWidth() {
return min_size;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
rectF.set(strokeWidth / 2f, strokeWidth / 2f, width - strokeWidth / 2f, MeasureSpec.getSize(heightMeasureSpec) - strokeWidth / 2f);
float radius = width / 2f;
float angle = (360 - arcAngle) / 2f;
arcBottomHeight = radius * (float) (1 - Math.cos(angle / 180 * Math.PI));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float startAngle = 270 - arcAngle / 2f;
float finishedSweepAngle = progress / (float) getMax() * arcAngle;
float finishedStartAngle = startAngle;
paint.setColor(unfinishedStrokeColor);
canvas.drawArc(rectF, startAngle, arcAngle, false, paint);
paint.setColor(finishedStrokeColor);
canvas.drawArc(rectF, finishedStartAngle, finishedSweepAngle, false, paint);
String text = String.valueOf(getProgress());
if (!TextUtils.isEmpty(text)) {
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
float textHeight = textPaint.descent() + textPaint.ascent();
float textBaseline = (getHeight() - textHeight) / 2.0f;
canvas.drawText(text, (getWidth() - textPaint.measureText(text)) / 2.0f, textBaseline, textPaint);
textPaint.setTextSize(suffixTextSize);
float suffixHeight = textPaint.descent() + textPaint.ascent();
canvas.drawText(suffixText, getWidth() / 2.0f + textPaint.measureText(text) + suffixTextPadding, textBaseline + textHeight - suffixHeight, textPaint);
}
if (!TextUtils.isEmpty(getBottomText())) {
textPaint.setTextSize(bottomTextSize);
float bottomTextBaseline = getHeight() - arcBottomHeight - (textPaint.descent() + textPaint.ascent()) / 2;
canvas.drawText(getBottomText(), (getWidth() - textPaint.measureText(getBottomText())) / 2.0f, bottomTextBaseline, textPaint);
}
}
#Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
bundle.putFloat(INSTANCE_STROKE_WIDTH, getStrokeWidth());
bundle.putFloat(INSTANCE_SUFFIX_TEXT_SIZE, getSuffixTextSize());
bundle.putFloat(INSTANCE_SUFFIX_TEXT_PADDING, getSuffixTextPadding());
bundle.putFloat(INSTANCE_BOTTOM_TEXT_SIZE, getBottomTextSize());
bundle.putString(INSTANCE_BOTTOM_TEXT, getBottomText());
bundle.putFloat(INSTANCE_TEXT_SIZE, getTextSize());
bundle.putInt(INSTANCE_TEXT_COLOR, getTextColor());
bundle.putInt(INSTANCE_PROGRESS, getProgress());
bundle.putInt(INSTANCE_MAX, getMax());
bundle.putInt(INSTANCE_FINISHED_STROKE_COLOR, getFinishedStrokeColor());
bundle.putInt(INSTANCE_UNFINISHED_STROKE_COLOR, getUnfinishedStrokeColor());
bundle.putFloat(INSTANCE_ARC_ANGLE, getArcAngle());
bundle.putString(INSTANCE_SUFFIX, getSuffixText());
return bundle;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if(state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
strokeWidth = bundle.getFloat(INSTANCE_STROKE_WIDTH);
suffixTextSize = bundle.getFloat(INSTANCE_SUFFIX_TEXT_SIZE);
suffixTextPadding = bundle.getFloat(INSTANCE_SUFFIX_TEXT_PADDING);
bottomTextSize = bundle.getFloat(INSTANCE_BOTTOM_TEXT_SIZE);
bottomText = bundle.getString(INSTANCE_BOTTOM_TEXT);
textSize = bundle.getFloat(INSTANCE_TEXT_SIZE);
textColor = bundle.getInt(INSTANCE_TEXT_COLOR);
setMax(bundle.getInt(INSTANCE_MAX));
setProgress(bundle.getInt(INSTANCE_PROGRESS));
finishedStrokeColor = bundle.getInt(INSTANCE_FINISHED_STROKE_COLOR);
unfinishedStrokeColor = bundle.getInt(INSTANCE_UNFINISHED_STROKE_COLOR);
suffixText = bundle.getString(INSTANCE_SUFFIX);
initPainters();
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
return;
}
super.onRestoreInstanceState(state);
}
}
I want to increase radius of arc and increase circumference of it .
Any hep wil be appreciated .
Thanx in advance :)
I want to increase radius of arc and increase circumference of it
Accordingly to the code you posted, the size is decide during onMeasure
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
rectF.set(strokeWidth / 2f, strokeWidth / 2f, width - strokeWidth / 2f, MeasureSpec.getSize(heightMeasureSpec) - strokeWidth / 2f);
float radius = width / 2f;
float angle = (360 - arcAngle) / 2f;
arcBottomHeight = radius * (float) (1 - Math.cos(angle / 180 * Math.PI));
}
So, in order to increase the radius, you have to increase width and height your provide in the layout. If you want to change the arc's color you can provide statically, in the xml
arc_finished_color and arc_unfinished_color
E.g.
<com.androidhive.musicplayer.equalizer.ArcProgress
android:id="#+id/songProgressBar"
android:background="#214193"
android:layout_marginLeft="50dp"
android:layout_width="100dp"
android:layout_height="100dp"
custom:arc_progress="55"
custom:arc_bottom_text="MEMORY"
custom:arc_finished_color="#color/finished_color"
custom:arc_unfinished_color="#color/unfinished_color"/>

Circular Image View stretched

I am using the following code for creating a circular image view within my project.
public class CircularImageView extends ImageView {
// Border & Selector configuration variables
private boolean hasBorder;
private boolean hasSelector;
private boolean isSelected;
private int borderWidth;
private int canvasSize;
private int selectorStrokeWidth;
// Objects used for the actual drawing
private BitmapShader shader;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private Paint paintSelectorBorder;
private ColorFilter selectorFilter;
public CircularImageView(Context context) {
this(context, null);
}
public CircularImageView(Context context, AttributeSet attrs)
{
this(context, attrs, R.attr.circularImageViewStyle);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
/**
* Initializes paint objects and sets desired attributes.
*
* #param context
* #param attrs
* #param defStyle
*/
private void init(Context context, AttributeSet attrs, int defStyle) {
// Initialize paint objects
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
paintSelectorBorder = new Paint();
paintSelectorBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
// Check if border and/or border is enabled
hasBorder = attributes.getBoolean(R.styleable.CircularImageView_border, false);
hasSelector = attributes.getBoolean(R.styleable.CircularImageView_selector, false);
// Set border properties if enabled
if(hasBorder) {
int defaultBorderSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
}
// Set selector properties if enabled
if(hasSelector) {
int defaultSelectorSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setSelectorColor(attributes.getColor(
R.styleable.CircularImageView_selector_color, Color.TRANSPARENT));
setSelectorStrokeWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_selector_stroke_width, defaultSelectorSize));
setSelectorStrokeColor(attributes.getColor(R.styleable.CircularImageView_selector_stroke_color, Color.BLUE));
}
// Add shadow if enabled
if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
addShadow();
// We no longer need our attributes TypedArray, give it back to cache
attributes.recycle();
}
/**
* Sets the CircularImageView's border width in pixels.
*
* #param borderWidth
*/
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
this.requestLayout();
this.invalidate();
}
/**
* Sets the CircularImageView's basic border color.
*
* #param borderColor
*/
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
/**
* Sets the color of the selector to be draw over the
* CircularImageView. Be sure to provide some opacity.
*
* #param selectorColor
*/
public void setSelectorColor(int selectorColor) {
this.selectorFilter = new PorterDuffColorFilter(selectorColor, PorterDuff.Mode.SRC_ATOP);
this.invalidate();
}
/**
* Sets the stroke width to be drawn around the CircularImageView
* during click events when the selector is enabled.
*
* #param selectorStrokeWidth
*/
public void setSelectorStrokeWidth(int selectorStrokeWidth) {
this.selectorStrokeWidth = selectorStrokeWidth;
this.requestLayout();
this.invalidate();
}
/**
* Sets the stroke color to be drawn around the CircularImageView
* during click events when the selector is enabled.
*
* #param selectorStrokeColor
*/
public void setSelectorStrokeColor(int selectorStrokeColor) {
if (paintSelectorBorder != null)
paintSelectorBorder.setColor(selectorStrokeColor);
this.invalidate();
}
/**
* Adds a dark shadow to this CircularImageView.
*/
public void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
// Don't draw anything without an image
if(image == null)
return;
// Nothing to draw (Empty bounds)
if(image.getHeight() == 0 || image.getWidth() == 0)
return;
// Compare canvas sizes
int oldCanvasSize = canvasSize;
canvasSize = canvas.getWidth();
if(canvas.getHeight() < canvasSize)
canvasSize = canvas.getHeight();
// Reinitialize shader, if necessary
if(oldCanvasSize != canvasSize)
refreshBitmapShader();
// Apply shader to paint
paint.setShader(shader);
// Keep track of selectorStroke/border width
int outerWidth = 0;
// Get the exact X/Y axis of the view
int center = canvasSize / 2;
if(hasSelector && isSelected) { // Draw the selector stroke & apply the selector filter, if applicable
outerWidth = selectorStrokeWidth;
center = (canvasSize - (outerWidth * 2)) / 2;
paint.setColorFilter(selectorFilter);
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, paintSelectorBorder);
}
else if(hasBorder) { // If no selector was drawn, draw a border and clear the filter instead... if enabled
outerWidth = borderWidth;
center = (canvasSize - (outerWidth * 2)) / 2;
paint.setColorFilter(null);
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, paintBorder);
}
else // Clear the color filter if no selector nor border were drawn
paint.setColorFilter(null);
// Draw the circular image itself
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) - 4.0f, paint);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
// Check for clickable state and do nothing if disabled
if(!this.isClickable()) {
this.isSelected = false;
return super.onTouchEvent(event);
}
// Set selected state based on Motion Event
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
this.isSelected = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_SCROLL:
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_CANCEL:
this.isSelected = false;
break;
}
// Redraw image and return super type
this.invalidate();
return super.dispatchTouchEvent(event);
}
public void invalidate(Rect dirty) {
super.invalidate(dirty);
image = drawableToBitmap(getDrawable());
if(shader != null || canvasSize > 0)
refreshBitmapShader();
}
public void invalidate(int l, int t, int r, int b) {
super.invalidate(l, t, r, b);
image = drawableToBitmap(getDrawable());
if(shader != null || canvasSize > 0)
refreshBitmapShader();
}
#Override
public void invalidate() {
super.invalidate();
image = drawableToBitmap(getDrawable());
if(shader != null || canvasSize > 0)
refreshBitmapShader();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
}
else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
}
else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
private int measureHeight(int measureSpecHeight) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
/**
* Convert a drawable object into a Bitmap
*
* #param drawable
* #return
*/
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) { // Don't do anything without a proper drawable
return null;
}
else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable
return ((BitmapDrawable) drawable).getBitmap();
}
// Create Bitmap object out of the drawable
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
/**
* Reinitializes the shader texture used to fill in
* the Circle upon drawing.
*/
public void refreshBitmapShader() {
shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
}
/**
* Returns whether or not this view is currently
* in its selected state.
*/
public boolean isSelected() {
return this.isSelected;
}
}
The circle effect is created, but the problem is all my pictures are being narrowed, as in the picture is too big and it's trying to fit in the circular image view. Any possible solutions to this? Thanks!
Assuming that the size of the circular image view is fixed, the only way to avoid stretching the image is to crop it to the same aspect ratio as the image view, or else introduce margins on the top or sides.
Since you are already scaling the bitmap to the canvas size inside refreshBitmapShader(), that is a convenient place to crop it using Bitmap.createBitmap():
public void refreshBitmapShader() {
int left = 0; y = 0; w = image.getWidth(), h = image.getHeight();
// decide whether we have to crop the sizes or the top and bottom:
if(w > h) // width is greater than height
{
x = (w - h) >> 1; // crop sides, half on each side
w = h;
}
else
{
y = (h - w) >> 1; // crop top and bottom
h = w;
}
Matrix m = new Matrix();
float scale = (float)canvasSize / (float)w;
m.preScale(scale, scale); // scale to canvas size
shader = new BitmapShader(Bitmap.createBitmap(image, x, y, w, h, m, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
}

How to work OSMDroid with Web Map Service (WMS) used by the private provider?

I'm trying to put the OSMDroid to work with WMS, but I do not find a way to put the WMS working.
Objective: OSMDroid working with WMS (projection EPSG:4326)
Tentative: I followed this example and include files: WMSMapTileProviderBasic, WMSMapTileDownloader, WMSTileSource, MapTile, and put the following code in my activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the mapview holder
LinearLayout mapHolder = (LinearLayout) findViewById(R.id.my_osmdroid_mapview);
// create a new WMS provider
final WMSMapTileProviderBasic tileProvider = new WMSMapTileProviderBasic(getApplicationContext());
// create the WMS tile source
final ITileSource tileSource = new WMSTileSource("WMS", null, 1, 20, 256, ".jpg", "http://myserver.com/geoserver/");
tileProvider.setTileSource(tileSource);
// create a new basic map view
MapView mapView = new MapView(this, 256, new DefaultResourceProxyImpl(this), tileProvider);
// add the layout params to the view so the map fills the screen
mapView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
// add the mapview to display
mapHolder.addView(mapView);
}
}
but did not show anything in map, why?
Thank you for your time.
You need to convert the ESPG:4326 to WebMercantor BB format. I have successfully used this code for doing that:
/*
* Sources http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
* code based on https://www.azavea.com/blog/2013/01/14/wms-on-android/
*/
public class WebMercatorBoundingBox {
double north;
double south;
double east;
double west;
// Web Mercator n/w corner of the map.
private static final double[] TILE_ORIGIN = {-20037508.34789244, 20037508.34789244};
//array indexes for that data
private static final int ORIG_X = 0;
private static final int ORIG_Y = 1; // "
// Size of square world map in meters, using WebMerc projection.
private static final double MAP_SIZE = 20037508.34789244 * 2;
protected WebMercatorBoundingBox(final int x, final int y, final int zoom) {
north = tile2lat(y, zoom);
south = tile2lat(y + 1, zoom);
west = tile2lon(x, zoom);
east = tile2lon(x + 1, zoom);
}
double tile2lon(int x, int z) {
double tileSize = MAP_SIZE / Math.pow(2.0, z);
return TILE_ORIGIN[ORIG_X] + x * tileSize;
}
double tile2lat(int y, int z) {
double tileSize = MAP_SIZE / Math.pow(2.0, z);
return TILE_ORIGIN[ORIG_Y] - y * tileSize;
}
public double getNorth(){
return this.north;
}
public double getSouth(){
return this.south;
}
public double getEast(){
return this.east;
}
public double getWest(){
return this.west;
}
}
Then you can create a tile with a WMSTileProvider source which extends the OnlineTileSourceBase and overrides the getTileURLString by converting it to the X,Y,Zoom to WebMercatorBoundingBox.
public class TileProviderFactory{
public static WMSTileProvider getWmsTileProvider(String version, String url, String layers, String fileFormat) {
String[] baseUrl = {url};
final String WMS_FORMAT_STRING =
url +
"?service=WMS" +
"&version=" + version +
"&request=GetMap" +
"&LAYERS=" + layers +
"&bbox=%f,%f,%f,%f" +
"&width=256" +
"&height=256" +
"&srs=EPSG:3857" +
"&format=" + fileFormat;
WMSTileProvider tileProvider = new WMSTileProvider(baseUrl, 256) {
#Override
public String getTileURLString(MapTile mapTile) {
WebMercatorBoundingBox bb = new WebMercatorBoundingBox(mapTile.getX(), mapTile.getY(), mapTile.getZoomLevel());
String s = String.format(
Locale.ENGLISH,
WMS_FORMAT_STRING,
bb.getWest(),
bb.getSouth(),
bb.getEast(),
bb.getNorth());
Log.d(TAG,"Fetching map tile: " + s);
return s;
}
};
return tileProvider;
}
}
public abstract class WMSTileProvider extends OnlineTileSourceBase {
// cql filters
private String cqlString = "";
// Construct with tile size in pixels, normally 256, see parent class.
public WMSTileProvider(String[] baseurl, int tileSizeInPixels) {
super("WMS tile source", 0 ,20,tileSizeInPixels,"png",baseurl);
}
protected String getCql() {
return URLEncoder.encode(cqlString);
}
public void setCql(String c) {
cqlString = c;
}
}

Displaying marquee-like scrolling text in Android

I'm working on Android app which main purpose is to display CNN breaking news styled bar on the bottom and some pictures. I created two custom views, one for displaying photos and the second one for displaying bar. It displays one picture at a time for specified amount of time and swaps current picture with next one from the queue.
To animate text in bottom bar I used canvas, onDraw() and handler.postDelayed. This solution gives poor result. Text movement is not smooth especially when it comes to swap image.
What should I use instead of canvas? Is there any OpenGL-based lib which could make this task relatively painless? I tried to use AndEngine, but its lack of documentation and problems with threads discouraged me to working with it anymore.
public class Infobar extends View {
private List<Message> messages;
private Handler handler;
private Paint boxPaint;
private Paint defaultTextPaint;
private Paint importantTextPaint;
private long offset = 0;
private long maxOffset = 1000;
private int textWidth = 1000;
private int textHeight = 50;
private int measuredWidth;
private int measuredHeight;
private Runnable animateRunnable = new Runnable() {
public void run() {
animateMessage();
}
};
long startTime = new Date().getTime();
private int backgroundCol = Color.parseColor("#ffff00");
private int textColor = Color.parseColor("#000000");
private static final int FRAME_DELAY = 10;
private static final int FRAME_SHIFT = 3;
private static final int EMPTY_SPACE = 2;
private static final String SEPARATOR = " ✩ ";
private static final int TEXT_SIZE = 35;
public Infobar(Context context, AttributeSet attrs) {
super(context, attrs);
handler = new Handler();
messages = new ArrayList<Message>();
boxPaint = new Paint();
defaultTextPaint = new Paint();
defaultTextPaint.setColor(getResources().getColor(R.color.info_bar_default_text_color));
importantTextPaint = new Paint();
importantTextPaint.setColor(getResources().getColor(R.color.info_bar_important_text_color));
handler.postDelayed(animateRunnable, FRAME_DELAY);
}
public void setMessagesList(List<Message> list) {
messages = list;
}
public void setBackgroundColor(String color) {
backgroundCol = Color.parseColor(color);
}
public void setTextColor(String color) {
textColor = Color.parseColor(color);
}
public List<Message> getMessagesList() {
return messages;
}
private String getMessagesString() {
StringBuilder builder = new StringBuilder();
for(Message message : messages) {
builder.append(message.content);
if(messages.indexOf(message) != (messages.size() - 1)) {
builder.append(SEPARATOR);
}
}
return builder.toString();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measuredWidth = getMeasuredWidth();
measuredHeight = getMeasuredHeight();
}
#Override
protected void onDraw(Canvas canvas) {
drawBackground(canvas, false);
drawMessage(canvas, getMessagesString());
super.onDraw(canvas);
}
private void drawBackground(Canvas canvas, boolean important) {
boxPaint.setColor(backgroundCol) ;
canvas.drawRect(0, 0, measuredWidth, measuredHeight, boxPaint);
}
private void drawMessage(Canvas canvas, String message) {
defaultTextPaint.setTextSize(TEXT_SIZE);
Rect bounds = new Rect();
defaultTextPaint.getTextBounds(message, 0, message.length(), bounds);
defaultTextPaint.setColor(textColor);
textWidth = bounds.width();
textHeight = bounds.height();
int positionX = measuredWidth - (int)offset;
int positionY = measuredHeight - textHeight/2;
if(offset > (measuredWidth + textWidth)) {
offset = 0;
positionX = measuredWidth;
}
canvas.drawText(message, positionX, positionY, defaultTextPaint);
}
private void animateMessage() {
offset += FRAME_SHIFT;
//offset = Math.round((new Date().getTime() - startTime) * 0.2) % (measuredWidth + textWidth);
invalidate();
handler.removeCallbacks(animateRunnable);
handler.postDelayed(animateRunnable, FRAME_DELAY);
}
}
Unless there is a specific reason, you can use the built-in marquee function of TextView:
<LinearLayout>
<TextView
android:id="#+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:text="Your long text goes here. You can also change it programmatically" />
</LinearLayout>
Then in the activity code:
TextView myText=(TextView) findViewById(R.id.myText);
myText.setSelected(true); //needs this to work

Categories