I've been working with a custom Seekbar (with two thumbs) taken from this site
I've did a couple of modifications with the code to adapt it to my needs and be a little more modular (thumb positioning, drawing, etc.). I've noticed that it was a bit glitchy when activities were created. Here are the symptoms of my problem.
When used in an activity (Android 4.0.3 - Asus transformer)
No issues at all, works 100%
When used in a fragment (Android 4.0.3 - Asus transformer)
Gray and blue (progress) lines are centered, thumbs are at top of the seekbar frame. (cut in half). They still work (sliding left to right with the proper progress line in the center)
Same application and activity as #1 (Android 4.2.2 - Galaxy Tab 3 10.1)
Both thumbs are in the center of the screen, you can't move them. Oddly, when you select one and move it from side to side, the seekbar value changed interface is called and the proper value is returned. When you release the selection of the thumb, the value sent to the listener returns to the center value.
Blank activity in a fresh application (Android 4.2.2 - Galaxy Tab 3 10.1)
The seekbar works 100%
Same behavior as #1 and #2 with a Google Nexus 7 LTE (2013) on Android 4.3.1
With this info, I can notice that the behavior varies from on activity to another depending on the amount of "stuff" included in it. I pretty sure it has to do with something about the measurements of the view. Probably the whole Init() method can be canned if the initialization is done properly overrinding the correct methods called during the creation of all the views in an activity or fragment.
Any ideas?
Thanks for your help!
Here is the complete Class:
public class SeekBarWithTwoThumb extends View {
// ***************
// Members
// ***************
// Drawing resources
private Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.drawable.seek_thumb_normal);
private Bitmap thumb_pressed = BitmapFactory.decodeResource(getResources(),R.drawable.seek_thumb_pressed);
private Bitmap thumb_dissabled = BitmapFactory.decodeResource(getResources(),R.drawable.seek_thumb_dissabled);
// Thumb's X coordinates and Y common coordinate
private int thumb1X, thumb2X;
private int thumbY;
// Thumb's return values
private int thumb1Value, thumb2Value;
// Thumb's dimensions
private int thumbHalfWidth;
private int thumbWidth;
// Selected thumb
private int selectedThumb;
private int lastSelectedThumb = 1;
// Paint object and listener
private Paint paint = new Paint();
private SeekBarChangeListener scl;
// Max value returned to listener
private int maxValue = 100;
// Thumb's enabled status
private boolean thumb1Enabled = true;
private boolean thumb2Enabled = false;
// Before init happens (not drawn in UI)
private boolean initDone = false;
private int thumb1Xpreset = 0, thumb2Xpreset = 50;
// ****************
// Constructors
// ****************
public SeekBarWithTwoThumb(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SeekBarWithTwoThumb(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SeekBarWithTwoThumb(Context context) {
super(context);
}
// ***************
// Overrides
// ***************
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if ((widthMeasureSpec != 0) && (heightMeasureSpec != 0)) {
init();
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Print the gray line in the back
paint.setStrokeWidth(1);
paint.setColor(Color.GRAY);
canvas.drawLine(thumbHalfWidth, getHeight() / 2, getWidth() - thumbHalfWidth, getHeight() / 2, paint);
// Print the progress line according seekbar settings
paint.setStrokeWidth(3);
paint.setColor(0xFF33B5E5); // Hollow blue
int drawThumbFirst = 0; // Variable used declare which thumb will be drawn first
if(thumb1Enabled && !thumb2Enabled) {
canvas.drawLine(thumbHalfWidth, getHeight() / 2, thumb1X, getHeight() / 2, paint);
drawThumbFirst = 2;
} else if (!thumb1Enabled && thumb2Enabled){
canvas.drawLine(thumbHalfWidth, getHeight() / 2, thumb2X, getHeight() / 2, paint);
drawThumbFirst = 1;
} else if (!thumb1Enabled && !thumb2Enabled) {
// Do not draw, both are disabled
} else if (selectedThumb == 1){
canvas.drawLine(thumbHalfWidth, getHeight() / 2, thumb1X, getHeight() / 2, paint);
} else if (selectedThumb == 2){
canvas.drawLine(thumbHalfWidth, getHeight() / 2, thumb2X, getHeight() / 2, paint);
} else if (lastSelectedThumb == 1){
canvas.drawLine(thumbHalfWidth, getHeight() / 2, thumb1X, getHeight() / 2, paint);
} else if (lastSelectedThumb == 2){
canvas.drawLine(thumbHalfWidth, getHeight() / 2, thumb2X, getHeight() / 2, paint);
}
if (drawThumbFirst == 2){
if (!thumb2Enabled) {
canvas.drawBitmap(thumb_dissabled, thumb2X - thumbHalfWidth, thumbY,paint);
} else if(selectedThumb == 2){
canvas.drawBitmap(thumb_pressed, thumb2X - thumbHalfWidth, thumbY,paint);
} else {
canvas.drawBitmap(thumb, thumb2X - thumbHalfWidth, thumbY,paint);
}
if (!thumb1Enabled) {
canvas.drawBitmap(thumb_dissabled, thumb1X - thumbHalfWidth, thumbY,paint);
} else if(selectedThumb == 1){
canvas.drawBitmap(thumb_pressed, thumb1X - thumbHalfWidth, thumbY,paint);
} else {
canvas.drawBitmap(thumb, thumb1X - thumbHalfWidth, thumbY,paint);
}
} else { // drawThumbFirst == 1 or 0 (0 has no importance since both thumbs either enabled or disabled)
if (!thumb1Enabled) {
canvas.drawBitmap(thumb_dissabled, thumb1X - thumbHalfWidth, thumbY,paint);
} else if(selectedThumb == 1){
canvas.drawBitmap(thumb_pressed, thumb1X - thumbHalfWidth, thumbY,paint);
} else {
canvas.drawBitmap(thumb, thumb1X - thumbHalfWidth, thumbY,paint);
}
if (!thumb2Enabled) {
canvas.drawBitmap(thumb_dissabled, thumb2X - thumbHalfWidth, thumbY,paint);
} else if(selectedThumb == 2){
canvas.drawBitmap(thumb_pressed, thumb2X - thumbHalfWidth, thumbY,paint);
} else {
canvas.drawBitmap(thumb, thumb2X - thumbHalfWidth, thumbY,paint);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Get X coordinate of event
int mx = (int) event.getX();
switch (event.getAction()) {
// Check if one of the thumbs are selected
case MotionEvent.ACTION_DOWN:
if (mx >= thumb1X - thumbHalfWidth &&
mx <= thumb1X + thumbHalfWidth &&
thumb1Enabled) {
selectedThumb = 1;
} else if (mx >= thumb2X - thumbHalfWidth &&
mx <= thumb2X + thumbHalfWidth &&
thumb2Enabled) {
selectedThumb = 2;
}
break;
// If one of the thumbs are selected, move it
case MotionEvent.ACTION_MOVE:
// Prevent thumb to get out of frame
if(mx < thumbHalfWidth){
mx = thumbHalfWidth;
} else if(mx > (getWidth() - thumbHalfWidth)) {
mx = getWidth() - thumbHalfWidth;
}
// Move the selected thumb to location
if (selectedThumb == 1) {
thumb1X = mx;
} else if (selectedThumb == 2) {
thumb2X = mx;
}
break;
// Remove selection, if any
case MotionEvent.ACTION_UP:
lastSelectedThumb = selectedThumb;
selectedThumb = 0;
break;
}
// Refresh
invalidate();
// Call listener if set
if(scl != null){
calculateThumbValue();
scl.SeekBarValueChanged(thumb1Value,thumb2Value);
}
return true;
}
// ***************
// Methods
// ***************
private void init() {
// Fix layout if thumb image is to big
Log.d("Custom Seekbars", "Height: " + thumb.getHeight() + ", " + getHeight());
if (thumb.getHeight() > getHeight()){
getLayoutParams().height = thumb.getHeight();
}
// Set the thumb's dimensions
thumbHalfWidth = thumb.getWidth()/2;
thumbWidth = thumb.getWidth();
// Set the thumb's coordinates
float workingWidth = getWidth() - thumbWidth;
float scale1 = ((float)(thumb1Xpreset))/((float)(maxValue));
float scale2 = ((float)(thumb2Xpreset))/((float)(maxValue));
thumb1X = Math.round((scale1*workingWidth) + thumbHalfWidth);
thumb2X = Math.round((scale2*workingWidth) + thumbHalfWidth);
thumbY = (getHeight() / 2) - (thumb.getHeight() / 2);
initDone = true;
// Refresh
invalidate();
}
public void setSeekBarChangeListener(SeekBarChangeListener scl){
this.scl = scl;
}
private void calculateThumbValue(){
thumb1Value = getThumb1Value();
thumb2Value = getThumb2Value();
}
public interface SeekBarChangeListener{
void SeekBarValueChanged(int Thumb1Value,int Thumb2Value);
}
public void setMax(int maxValue){
if(initDone){
int thumb1val = getThumb1Value();
int thumb2val = getThumb1Value();
this.maxValue = maxValue;
setThumbValues(thumb1val, thumb2val);
} else {
this.maxValue = maxValue;
}
}
// Disable & enable methods
public void setEnable(boolean value){
thumb1Enabled = value;
thumb2Enabled = value;
}
public void setDisable(boolean value){
thumb1Enabled = !value;
thumb2Enabled = !value;
}
public void setEnable(boolean thumb1, boolean thumb2){
thumb1Enabled = thumb1;
thumb2Enabled = thumb2;
}
public void setDisable(boolean thumb1, boolean thumb2){
thumb1Enabled = !thumb1;
thumb2Enabled = !thumb2;
}
// Thumb value setters and getters
public void setThumbValues(int thumb1, int thumb2){
if(initDone){
if(thumb1 >= maxValue){
thumb1X = getWidth() - thumbHalfWidth;
} else if(thumb1 <= 0) {
thumb1X = thumbHalfWidth;
} else {
float workingWidth = getWidth() - thumbWidth;
float scale = ((float)(thumb1))/((float)(maxValue));
thumb1X = Math.round((scale*workingWidth) + thumbHalfWidth);
}
if(thumb2 >= maxValue){
thumb2X = getWidth() - thumbHalfWidth;
} else if(thumb2 <= 0) {
thumb2X = thumbHalfWidth;
} else {
float workingWidth = getWidth() - thumbWidth;
float scale = ((float)(thumb2))/((float)(maxValue));
thumb2X = Math.round((scale*workingWidth) + thumbHalfWidth);
}
// Refresh
invalidate();
// Call listener if set
if(scl != null){
calculateThumbValue();
scl.SeekBarValueChanged(thumb1Value,thumb2Value);
}
} else {
if(thumb1 >= maxValue){
thumb1Xpreset = maxValue;
} else if(thumb1 <= 0) {
thumb1Xpreset = 0;
} else {
thumb1Xpreset = thumb1;
}
if(thumb2 >= maxValue){
thumb2Xpreset = maxValue;
} else if(thumb2 <= 0) {
thumb2Xpreset = 0;
} else {
thumb2Xpreset = thumb2;
}
}
}
public void setThumb1Value(int value){
if(initDone){
if(value >= maxValue){
thumb1X = getWidth() - thumbHalfWidth;
} else if(value <= 0) {
thumb1X = thumbHalfWidth;
} else {
float workingWidth = getWidth() - thumbWidth;
float scale = ((float)(value))/((float)(maxValue));
thumb1X = Math.round((scale*workingWidth) + thumbHalfWidth);
}
// Refresh
invalidate();
// Call listener if set
if(scl != null){
calculateThumbValue();
scl.SeekBarValueChanged(thumb1Value,thumb2Value);
}
} else {
if(value >= maxValue){
thumb1Xpreset = maxValue;
} else if(value <= 0) {
thumb1Xpreset = 0;
} else {
thumb1Xpreset = value;
}
}
}
public void setThumb2Value(int value){
if(initDone){
if(value >= maxValue){
thumb2X = getWidth() - thumbHalfWidth;
} else if(value <= 0) {
thumb2X = thumbHalfWidth;
} else {
float workingWidth = getWidth() - thumbWidth;
float scale = ((float)(value))/((float)(maxValue));
thumb2X = Math.round((scale*workingWidth) + thumbHalfWidth);
}
// Refresh
invalidate();
// Call listener if set
if(scl != null){
calculateThumbValue();
scl.SeekBarValueChanged(thumb1Value,thumb2Value);
}
} else {
if(value >= maxValue){
thumb2Xpreset = maxValue;
} else if(value <= 0) {
thumb2Xpreset = 0;
} else {
thumb2Xpreset = value;
}
}
}
public int getThumb1Value(){
if(initDone){
float workingWidth = getWidth() - thumbWidth;
return Math.round((float)maxValue * ((float)(thumb1X - thumbHalfWidth)/workingWidth));
} else {
return thumb1Xpreset;
}
}
public int getThumb2Value(){
if(initDone){
float workingWidth = getWidth() - thumbWidth;
return Math.round((float)maxValue * ((float)(thumb2X - thumbHalfWidth)/workingWidth));
} else {
return thumb2Xpreset;
}
}
}
Related
I am creating an application. If the custom View goes off the screen, a method is called. Here is my code for the custom View.
public class CustomView extends View {
private boolean bubbleOver;
private static final int BITMAP_SIZE = 64;
private static final int REFRESH_RATE = 40;
private final Paint mPainter = new Paint();
private ScheduledFuture<?> mMoverFuture;
private int mScaledBitmapWidth;
private Bitmap mScaledBitmap;
// location, speed and direction of the bubble
private float mXPos, mYPos, mDx, mDy, mRadius, mRadiusSquared;
private long mRotate, mDRotate;
CustomView (Context context, float x, float y) {
super (context);
// Create a new random number generator to randomize size, rotation, speed and direction
Random r = new Random ();
// Creates the bubble bitmap for this BubbleView
createScaledBitmap (r);
// Radius of the Bitmap
mRadius = mScaledBitmapWidth / 2;
mRadiusSquared = mRadius * mRadius;
// Adjust position to center the bubble under user's finger
mXPos = x - mRadius;
mYPos = y - mRadius;
// Set the BubbleView's speed and direction
setSpeedAndDirection(r);
// Set the BubbleView's rotation
setRotation(r);
mPainter.setAntiAlias(true);
}
private void setRotation(Random r) {
if (speedMode == RANDOM) {
// TODO - set rotation in range [1..3]
mDRotate = r.nextInt (3) + 1;
} else {
mDRotate = 0;
}
}
private void setSpeedAndDirection(Random r) {
// Used by test cases
switch (speedMode) {
case SINGLE:
mDx = 20;
mDy = 20;
break;
case STILL:
// No speed
mDx = 0;
mDy = 0;
break;
default:
// Limit movement speed in the x and y direction to [-3..3] pixels per movement.
mDx = r.nextFloat() * 6.0f - 3.0f;
mDy = r.nextFloat() * 6.0f - 3.0f;
}
}
private void createScaledBitmap (Random r) {
if (speedMode != RANDOM) {
mScaledBitmapWidth = BITMAP_SIZE * 3;
} else {
mScaledBitmapWidth = (r.nextInt(3) + 1) * BITMAP_SIZE;
}
mScaledBitmap = Bitmap.createScaledBitmap(mBitmap, mScaledBitmapWidth, mScaledBitmapWidth, true);
}
// Start moving the BubbleView & updating the display
private void start () {
// Creates a WorkerThread
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// Execute the run() in Worker Thread every REFRESH_RATE milliseconds. Save reference to this job in mMoverFuture
mMoverFuture = executor.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
if (moveWhileOnScreen()) {
stop (false);
} else {
BubbleView.this.postInvalidate();
}
}
}, 0, REFRESH_RATE, TimeUnit.MILLISECONDS);
}
// Returns true if the BubbleView intersects position (x,y)
private synchronized boolean intersects(float x, float y) {
// TODO - Return true if the BubbleView intersects position (x,y)
if ((mXPos <= x) && (x <= mXPos + mScaledBitmapWidth) && (mYPos <= y) && (y <= mYPos + mScaledBitmapWidth)) {
return true;
}
return false;
}
// Cancel the Bubble's movement. Remove Bubble from mFrame.
// Play pop sound if the BubbleView was popped
private void stop (final boolean wasPopped) {
if (null != mMoverFuture && !mMoverFuture.isDone()) {
mMoverFuture.cancel(true);
}
// This work will be performed on the UI Thread
mFrame.post(new Runnable() {
#Override
public void run() {
mFrame.removeView(BubbleView.this);
if (wasPopped) {
mSoundPool.play(mSoundID, mStreamVolume, mStreamVolume, 1, 0, 1f);
}
}
});
}
// Change the Bubble's speed and direction
private synchronized void deflect(float velocityX, float velocityY) {
mDx = velocityX / REFRESH_RATE;
mDy = velocityY / REFRESH_RATE;
}
// Draw the Bubble at its current location
#Override
protected synchronized void onDraw(Canvas canvas) {
canvas.save();
mRotate += mDRotate;
canvas.rotate(mRotate, mXPos + (mScaledBitmapWidth / 2), mYPos + (mScaledBitmapWidth / 2));
canvas.drawBitmap(mScaledBitmap, mXPos, mYPos, mPainter);
canvas.restore();
}
// Returns true if the BubbleView is still on the screen after the move operation
private synchronized boolean moveWhileOnScreen() {
mXPos += mDx;
mYPos += mDy;
return isOutOfView();
}
// Return true if the BubbleView is off the screen after the move operation
private boolean isOutOfView() {
if ((mXPos + mDisplayWidth < 0) || (mYPos + mDisplayHeight < 0) || (mXPos> mDisplayWidth) || (mYPos > mDisplayHeight)) {
loseGame();
return true;
}
return false;
}
}
When the View goes off the screen, loseGame() is not called. Only if another CustomView is created, loseGame() is called.
You have wrong sum to check, try with mScaledBitmapWidth not the mDisplayWidth.
if ((mXPos + mScaledBitmapWidth < 0)
|| (mYPos + mScaledBitmapWidth < 0)
|| (mXPos> mDisplayWidth)
|| (mYPos > mDisplayHeight)
{
loseGame();
return true;
}
Basically, I cloned a material design widget library and wanted to use the Seekbar view. Even when using match_parent for the width, there was still some padding on the left and right. To combat this, I cloned the project from GitHub and went to the Slider.java class to try and figure out how to truly make this a full length media SeekBar.
I've included my current code, which basically shows a full length seekbar, but starts it a little to the right from the beginning (and consequently stops a little to the left from the end). Here it is mid-media-playback:
CODE
public class Slider extends CustomView {
private int backgroundColor = Color.parseColor("#614E8D");
private Ball ball;
private Bitmap bitmap;
private int max = 100;
private int min = 0;
private NumberIndicator numberIndicator;
private OnValueChangedListener onValueChangedListener;
private boolean placedBall = false;
private boolean press = false;
private boolean showNumberIndicator = false;
private int value = 0;
public Slider(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(attrs);
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public OnValueChangedListener getOnValueChangedListener() {
return onValueChangedListener;
}
public void setOnValueChangedListener(
OnValueChangedListener onValueChangedListener) {
this.onValueChangedListener = onValueChangedListener;
}
// GETERS & SETTERS
public int getValue() {
return value;
}
public void setValue(final int value) {
if (placedBall == false)
post(new Runnable() {
#Override
public void run() {
setValue(value);
}
});
else {
this.value = value;
float division = (ball.xFin - ball.xIni) / max;
ViewHelper.setX(ball,
value * division + getHeight() / 2 - ball.getWidth() / 2);
ball.changeBackground();
}
}
#Override
public void invalidate() {
ball.invalidate();
super.invalidate();
}
public boolean isShowNumberIndicator() {
return showNumberIndicator;
}
public void setShowNumberIndicator(boolean showNumberIndicator) {
this.showNumberIndicator = showNumberIndicator;
numberIndicator = (showNumberIndicator) ? new NumberIndicator(
getContext()) : null;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
isLastTouch = true;
if (isEnabled()) {
if (event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE) {
if (numberIndicator != null
&& numberIndicator.isShowing() == false)
numberIndicator.show();
if ((event.getX() <= getWidth() && event.getX() >= 0)) {
press = true;
// calculate value
int newValue = 0;
float division = (ball.xFin - ball.xIni) / (max - min);
if (event.getX() > ball.xFin) {
newValue = max;
} else if (event.getX() < ball.xIni) {
newValue = min;
} else {
newValue = min + (int) ((event.getX() - ball.xIni) / division);
}
if (value != newValue) {
value = newValue;
if (onValueChangedListener != null)
onValueChangedListener.onValueChanged(newValue);
}
// move ball indicator
float x = event.getX();
x = (x < ball.xIni) ? ball.xIni : x;
x = (x > ball.xFin) ? ball.xFin : x;
ViewHelper.setX(ball, x);
ball.changeBackground();
// If slider has number indicator
if (numberIndicator != null) {
// move number indicator
numberIndicator.indicator.x = x;
numberIndicator.indicator.finalY = Utils
.getRelativeTop(this) - getHeight() / 2;
numberIndicator.indicator.finalSize = getHeight() / 2;
numberIndicator.numberIndicator.setText("");
}
} else {
press = false;
isLastTouch = false;
if (numberIndicator != null)
numberIndicator.dismiss();
}
} else if (event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
if (numberIndicator != null)
numberIndicator.dismiss();
isLastTouch = false;
press = false;
}
}
return true;
}
#Override
public void setBackgroundColor(int color) {
backgroundColor = color;
if (isEnabled())
beforeBackground = backgroundColor;
}
/**
* Make a dark color to press effect
*
* #return
*/
protected int makePressColor() {
int r = (this.backgroundColor >> 16) & 0xFF;
int g = (this.backgroundColor >> 8) & 0xFF;
int b = (this.backgroundColor >> 0) & 0xFF;
r = (r - 30 < 0) ? 0 : r - 30;
g = (g - 30 < 0) ? 0 : g - 30;
b = (b - 30 < 0) ? 0 : b - 30;
return Color.argb(70, r, g, b);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!placedBall) {
placeBall();
}
Paint paint = new Paint();
if (value == min) {
// Crop line to transparent effect
// before song loaded, basically. Need to make this similar to value != min
if (bitmap == null) {
bitmap = Bitmap.createBitmap(canvas.getWidth(),
canvas.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas temp = new Canvas(bitmap);
paint.setColor(Color.parseColor("#54457A")); //purple
paint.setStrokeWidth(Utils.dpToPx(2, getResources()));
// temp.drawLine(getHeight() / 2, getHeight() / 2, getWidth()
// - getHeight() / 2, getHeight() / 2, paint);
temp.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2, paint);
Paint transparentPaint = new Paint();
transparentPaint.setColor(getResources().getColor(
android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
temp.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
ViewHelper.getY(ball) + ball.getHeight() / 2,
ball.getWidth() / 2, transparentPaint);
canvas.drawBitmap(bitmap, 0, 0, new Paint());
} else {
/*TRACK*/
paint.setColor(Color.parseColor("#5A5A5C")); //track
paint.setStrokeWidth(Utils.dpToPx(10, getResources()));
canvas.drawLine(0, getHeight()/2, getWidth(), getHeight()/2, paint); //track length
paint.setColor(backgroundColor);
/*END TRACK*/
float division = (ball.xFin - ball.xIni) / (max - min);
int value = this.value - min;
//DO NOT TOUCH -- Progress coloring
canvas.drawLine(getHeight() / 2, getHeight() / 2, value * division
+ getHeight() / 2, getHeight() / 2, paint);
}
if (press && !showNumberIndicator) {
paint.setColor(backgroundColor);
paint.setAntiAlias(true);
canvas.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
getHeight() / 2, getHeight() / 3, paint);
}
invalidate();
}
// Set atributtes of XML to View
protected void setAttributes(AttributeSet attrs) {
setBackgroundResource(R.drawable.background_transparent);
// Set size of view
setMinimumHeight(Utils.dpToPx(48, getResources()));
setMinimumWidth(Utils.dpToPx(80, getResources()));
// Set background Color
// Color by resource
int bacgroundColor = attrs.getAttributeResourceValue(ANDROIDXML,
"background", -1);
if (bacgroundColor != -1) {
setBackgroundColor(getResources().getColor(bacgroundColor));
} else {
// Color by hexadecimal
int background = attrs.getAttributeIntValue(ANDROIDXML, "background", -1);
if (background != -1)
setBackgroundColor(background);
}
showNumberIndicator = attrs.getAttributeBooleanValue(MATERIALDESIGNXML,
"showNumberIndicator", false);
min = attrs.getAttributeIntValue(MATERIALDESIGNXML, "min", 0);
max = attrs.getAttributeIntValue(MATERIALDESIGNXML, "max", 0);
value = attrs.getAttributeIntValue(MATERIALDESIGNXML, "value", min);
ball = new Ball(getContext());
RelativeLayout.LayoutParams params = new LayoutParams(Utils.dpToPx(20,
getResources()), Utils.dpToPx(20, getResources()));
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
ball.setLayoutParams(params);
addView(ball);
// Set if slider content number indicator
// TODO
if (showNumberIndicator) {
numberIndicator = new NumberIndicator(getContext());
}
}
private void placeBall() {
ViewHelper.setX(ball, getHeight() / 2 - ball.getWidth() / 2);
ViewHelper.setX(ball, ball.getWidth());
ball.xIni = ViewHelper.getX(ball);
ball.xFin = getWidth() - ball.getWidth();// - getHeight() / 2 - ball.getWidth() / 2;
ball.xCen = getWidth() / 2 - ball.getWidth() / 2;
placedBall = true;
}
// Event when slider change value
public interface OnValueChangedListener {
public void onValueChanged(int value);
}
class Ball extends View {
float xIni, xFin, xCen;
public Ball(Context context) {
super(context);
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
public void changeBackground() {
if (value != min) {
setBackgroundResource(R.drawable.background_checkbox);
LayerDrawable layer = (LayerDrawable) getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(Color.parseColor("#D5C46A")); //yellow ball
} else {
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
}
}
// Slider Number Indicator
class Indicator extends RelativeLayout {
boolean animate = true;
// Final size after animation
float finalSize = 0;
// Final y position after animation
float finalY = 0;
boolean numberIndicatorResize = false;
// Size of number indicator
float size = 0;
// Position of number indicator
float x = 0;
float y = 0;
public Indicator(Context context) {
super(context);
setBackgroundColor(getResources().getColor(
android.R.color.transparent));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (numberIndicatorResize == false) {
LayoutParams params = (LayoutParams) numberIndicator.numberIndicator
.getLayoutParams();
params.height = (int) finalSize * 2;
params.width = (int) finalSize * 2;
numberIndicator.numberIndicator.setLayoutParams(params);
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(backgroundColor);
if (animate) {
if (y == 0)
y = finalY + finalSize * 2;
y -= Utils.dpToPx(6, getResources());
size += Utils.dpToPx(2, getResources());
}
canvas.drawCircle(
ViewHelper.getX(ball)
+ Utils.getRelativeLeft((View) ball.getParent())
+ ball.getWidth() / 2, y, size, paint);
if (animate && size >= finalSize)
animate = false;
if (animate == false) {
ViewHelper
.setX(numberIndicator.numberIndicator,
(ViewHelper.getX(ball)
+ Utils.getRelativeLeft((View) ball
.getParent()) + ball.getWidth() / 2)
- size);
ViewHelper.setY(numberIndicator.numberIndicator, y - size);
numberIndicator.numberIndicator.setText(value + "");
}
invalidate();
}
}
class NumberIndicator extends Dialog {
Indicator indicator;
TextView numberIndicator;
public NumberIndicator(Context context) {
super(context, android.R.style.Theme_Translucent);
}
#Override
public void dismiss() {
super.dismiss();
indicator.y = 0;
indicator.size = 0;
indicator.animate = true;
}
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.number_indicator_spinner);
setCanceledOnTouchOutside(false);
RelativeLayout content = (RelativeLayout) this
.findViewById(R.id.number_indicator_spinner_content);
indicator = new Indicator(this.getContext());
content.addView(indicator);
numberIndicator = new TextView(getContext());
numberIndicator.setTextColor(Color.WHITE);
numberIndicator.setGravity(Gravity.CENTER);
content.addView(numberIndicator);
indicator.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
}
}
}
Any help on how to get the circle to start at the very left and end at the very right would be greatly appreciated.
Playing around some more, I found that the original developer of this Slider.java class used a lot of getHeight() / 2 which caused some padding that I didn't want. I've included the edited class. Credit for original class to navasmdc, the creator of Material Design Library.. Feel free to use this class if you need a full sized SeekBar
Slider.java
package com.gc.materialdesign.views;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gc.materialdesign.R;
import com.gc.materialdesign.utils.Utils;
import com.nineoldandroids.view.ViewHelper;
public class Slider extends CustomView {
private int backgroundColor = Color.parseColor("#614E8D");
private Ball ball;
private Bitmap bitmap;
private int max = 100;
private int min = 0;
private NumberIndicator numberIndicator;
private OnValueChangedListener onValueChangedListener;
private boolean placedBall = false;
private boolean press = false;
private boolean showNumberIndicator = false;
private int value = 0;
public Slider(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(attrs);
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public OnValueChangedListener getOnValueChangedListener() {
return onValueChangedListener;
}
public void setOnValueChangedListener(
OnValueChangedListener onValueChangedListener) {
this.onValueChangedListener = onValueChangedListener;
}
// GETERS & SETTERS
public int getValue() {
return value;
}
public void setValue(final int value) {
if (placedBall == false)
post(new Runnable() {
#Override
public void run() {
setValue(value);
}
});
else {
this.value = value;
float division = (ball.xFin - ball.xIni) / max;
ViewHelper.setX(ball,
value* division);//value * division - ball.getWidth() / 2);
ball.changeBackground();
}
}
#Override
public void invalidate() {
ball.invalidate();
super.invalidate();
}
public boolean isShowNumberIndicator() {
return showNumberIndicator;
}
public void setShowNumberIndicator(boolean showNumberIndicator) {
this.showNumberIndicator = showNumberIndicator;
numberIndicator = (showNumberIndicator) ? new NumberIndicator(
getContext()) : null;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
isLastTouch = true;
if (isEnabled()) {
if (event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE) {
if (numberIndicator != null
&& numberIndicator.isShowing() == false)
numberIndicator.show();
if ((event.getX() <= getWidth() && event.getX() >= 0)) {
press = true;
// calculate value
int newValue = 0;
float division = (ball.xFin - ball.xIni) / (max - min);
if (event.getX() > ball.xFin) {
newValue = max;
} else if (event.getX() < ball.xIni) {
newValue = min;
} else {
newValue = min + (int) ((event.getX() - ball.xIni) / division);
}
if (value != newValue) {
value = newValue;
if (onValueChangedListener != null)
onValueChangedListener.onValueChanged(newValue);
}
// move ball indicator
float x = event.getX();
x = (x < ball.xIni) ? ball.xIni : x;
x = (x > ball.xFin) ? ball.xFin : x;
ViewHelper.setX(ball, x);
ball.changeBackground();
// If slider has number indicator
if (numberIndicator != null) {
// move number indicator
numberIndicator.indicator.x = x;
numberIndicator.indicator.finalY = Utils
.getRelativeTop(this) - getHeight() / 2;
numberIndicator.indicator.finalSize = getHeight() / 2;
numberIndicator.numberIndicator.setText("");
}
} else {
press = false;
isLastTouch = false;
if (numberIndicator != null)
numberIndicator.dismiss();
}
} else if (event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
if (numberIndicator != null)
numberIndicator.dismiss();
isLastTouch = false;
press = false;
}
}
return true;
}
#Override
public void setBackgroundColor(int color) {
backgroundColor = color;
if (isEnabled())
beforeBackground = backgroundColor;
}
/**
* Make a dark color to press effect
*
* #return
*/
protected int makePressColor() {
int r = (this.backgroundColor >> 16) & 0xFF;
int g = (this.backgroundColor >> 8) & 0xFF;
int b = (this.backgroundColor >> 0) & 0xFF;
r = (r - 30 < 0) ? 0 : r - 30;
g = (g - 30 < 0) ? 0 : g - 30;
b = (b - 30 < 0) ? 0 : b - 30;
return Color.argb(70, r, g, b);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!placedBall) {
placeBall();
}
Paint paint = new Paint();
if (value == min) {
// Crop line to transparent effect
// before song loaded, basically. Need to make this similar to value != min
if (bitmap == null) {
bitmap = Bitmap.createBitmap(canvas.getWidth(),
canvas.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas temp = new Canvas(bitmap);
paint.setColor(Color.parseColor("#54457A")); //purple
paint.setStrokeWidth(Utils.dpToPx(2, getResources()));
// temp.drawLine(getHeight() / 2, getHeight() / 2, getWidth()
// - getHeight() / 2, getHeight() / 2, paint);
temp.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2, paint);
Paint transparentPaint = new Paint();
transparentPaint.setColor(getResources().getColor(
android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
temp.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
ViewHelper.getY(ball) + ball.getHeight() / 2,
ball.getWidth() / 2, transparentPaint);
canvas.drawBitmap(bitmap, 0, 0, new Paint());
} else {
/*TRACK*/
paint.setColor(Color.parseColor("#5A5A5C")); //track
paint.setStrokeWidth(Utils.dpToPx(10, getResources()));
canvas.drawLine(0, getHeight()/2, getWidth(), getHeight()/2, paint); //track length
paint.setColor(backgroundColor);
/*END TRACK*/
float division = (ball.xFin - ball.xIni) / (max - min);
int value = this.value - min;
//DO NOT TOUCH -- Progress coloring
canvas.drawLine(0, getHeight() / 2, value * division
+ball.getWidth(), getHeight() / 2, paint);
}
if (press && !showNumberIndicator) {
paint.setColor(backgroundColor);
paint.setAntiAlias(true);
canvas.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
getHeight() / 2, getHeight() / 3, paint);
}
invalidate();
}
// Set atributtes of XML to View
protected void setAttributes(AttributeSet attrs) {
setBackgroundResource(R.drawable.background_transparent);
// Set size of view
setMinimumHeight(Utils.dpToPx(48, getResources()));
setMinimumWidth(Utils.dpToPx(80, getResources()));
// Set background Color
// Color by resource
int bacgroundColor = attrs.getAttributeResourceValue(ANDROIDXML,
"background", -1);
if (bacgroundColor != -1) {
setBackgroundColor(getResources().getColor(bacgroundColor));
} else {
// Color by hexadecimal
int background = attrs.getAttributeIntValue(ANDROIDXML, "background", -1);
if (background != -1)
setBackgroundColor(background);
}
showNumberIndicator = attrs.getAttributeBooleanValue(MATERIALDESIGNXML,
"showNumberIndicator", false);
min = attrs.getAttributeIntValue(MATERIALDESIGNXML, "min", 0);
max = attrs.getAttributeIntValue(MATERIALDESIGNXML, "max", 0);
value = attrs.getAttributeIntValue(MATERIALDESIGNXML, "value", min);
ball = new Ball(getContext());
RelativeLayout.LayoutParams params = new LayoutParams(Utils.dpToPx(20,
getResources()), Utils.dpToPx(20, getResources()));
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
ball.setLayoutParams(params);
addView(ball);
// Set if slider content number indicator
// TODO
if (showNumberIndicator) {
numberIndicator = new NumberIndicator(getContext());
}
}
private void placeBall() {
// ViewHelper.setX(ball, getHeight() / 2 - ball.getWidth() / 2);
// ViewHelper.setX(ball, 0);
ViewHelper.setX(ball, ball.getWidth());
ball.xIni = 0;//ViewHelper.getX(ball);
ball.xFin = getWidth() - ball.getWidth();// - getHeight() / 2 - ball.getWidth() / 2;
ball.xCen = getWidth() / 2 - ball.getWidth() / 2;
placedBall = true;
}
// Event when slider change value
public interface OnValueChangedListener {
public void onValueChanged(int value);
}
class Ball extends View {
float xIni, xFin, xCen;
public Ball(Context context) {
super(context);
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
public void changeBackground() {
if (value != min) {
setBackgroundResource(R.drawable.background_checkbox);
LayerDrawable layer = (LayerDrawable) getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(Color.parseColor("#D5C46A")); //yellow ball
} else {
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
}
}
// Slider Number Indicator
class Indicator extends RelativeLayout {
boolean animate = true;
// Final size after animation
float finalSize = 0;
// Final y position after animation
float finalY = 0;
boolean numberIndicatorResize = false;
// Size of number indicator
float size = 0;
// Position of number indicator
float x = 0;
float y = 0;
public Indicator(Context context) {
super(context);
setBackgroundColor(getResources().getColor(
android.R.color.transparent));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (numberIndicatorResize == false) {
LayoutParams params = (LayoutParams) numberIndicator.numberIndicator
.getLayoutParams();
params.height = (int) finalSize * 2;
params.width = (int) finalSize * 2;
numberIndicator.numberIndicator.setLayoutParams(params);
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(backgroundColor);
if (animate) {
if (y == 0)
y = finalY + finalSize * 2;
y -= Utils.dpToPx(6, getResources());
size += Utils.dpToPx(2, getResources());
}
canvas.drawCircle(
ViewHelper.getX(ball)
+ Utils.getRelativeLeft((View) ball.getParent())
+ ball.getWidth() / 2, y, size, paint);
if (animate && size >= finalSize)
animate = false;
if (animate == false) {
ViewHelper
.setX(numberIndicator.numberIndicator,
(ViewHelper.getX(ball)
+ Utils.getRelativeLeft((View) ball
.getParent()) + ball.getWidth() / 2)
- size);
ViewHelper.setY(numberIndicator.numberIndicator, y - size);
numberIndicator.numberIndicator.setText(value + "");
}
invalidate();
}
}
class NumberIndicator extends Dialog {
Indicator indicator;
TextView numberIndicator;
public NumberIndicator(Context context) {
super(context, android.R.style.Theme_Translucent);
}
#Override
public void dismiss() {
super.dismiss();
indicator.y = 0;
indicator.size = 0;
indicator.animate = true;
}
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.number_indicator_spinner);
setCanceledOnTouchOutside(false);
RelativeLayout content = (RelativeLayout) this
.findViewById(R.id.number_indicator_spinner_content);
indicator = new Indicator(this.getContext());
content.addView(indicator);
numberIndicator = new TextView(getContext());
numberIndicator.setTextColor(Color.WHITE);
numberIndicator.setGravity(Gravity.CENTER);
content.addView(numberIndicator);
indicator.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
}
}
}
I have a custom View and I wonder, is there any chace that I could detect if something outside of my View is clicked. It MUST be in the View class, or else it can not work as I intended it to!
Full file: https://github.com/Nicba1010/AndroidLibrary/blob/master/src/com/nicba1010/utils/views/PieChartView.java
OnTouchEvent(so you know I did something)
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
selected = null;
invalidate();
return true;
}
double deltaX = event.getX() - rect.width() / 2 - rect.left;
double deltaY = -(event.getY() - rect.height() / 2 - rect.top);
double fromMid = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
boolean inCircle = fromMid < (rectSelect.bottom / 2);
if (inCircle) {
double angleInDegrees = getPositionOnCircumference(deltaX, deltaY);
float percentage = (float) (angleInDegrees / 360f);
float totalPerc = 0;
int index = -1, i = 0;
for (PieChartSlice e : slices) {
if (percentage > totalPerc) {
index = i;
} else if (percentage < totalPerc) {
break;
}
totalPerc += e.getPercentage();
i++;
}
if (index == -1) {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
} else {
final PieChartSlice tmp = slices.get(index);
addScaleTask(rect, 500, 0.9f, new Runnable() {
#Override
public void run() {
selected = tmp;
}
});
selected = slices.get(index);
invalidate();
Toast.makeText(getContext(), selected.getName(),
Toast.LENGTH_SHORT).show();
onSliceSelectedListener.onSliceSelected(this, selected);
}
} else {
if (selected != null) {
addScaleTask(rect, 500, 1f, new Runnable() {
#Override
public void run() {
selected = null;
}
});
invalidate();
}
}
return super.onTouchEvent(event);
}
View has the getHitRect(Rect) method. You can use to retrieve it hit rect of this view and you can use this rect to check it the MotionEvent it is inside it. For instance
Rect rect = new Rect();
getHitRect(rect);
if (rect.contains((int) event.getX(), (int) event.getY()) {
}
I have a custom view, and within the custom view I create 4 text views. I want each of these text views to respond to on touch events. However, the textviews themselves do not respond to an on touch event. I can however, make an ontouch listener for the entire custom view. However, I do not want the whole view to have an ontouch event because I want the textviews that I have created to be dragged and dropped. I tried going the route of registering the x and y coordinates of the ontouch event and assuming that if the ontouch event is within the bounds of a textview, to change the coordinates of the textview, but that was overly complicated because if one textview got dragged to the coordinates of another one, then the ontouch event would "pick up" the other textview, so then I'd be moving two text views, which is not what I want. So, to sum it up, I want to know if it's possible to set in ontouch listener for a textview inside a customview, and if possible, why it is not working:
mScale.mPositive.get(0).setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScale.mCurrentXPos[0] = event.getX();
mScale.mCurrentYPos[0] = event.getY();
mScale.mDrag = true;
return true;
}
});
This same code works for the custom view, but not for the specific textviews inside that customview.
Here is the custom view code:
public class Scale extends View
{
public Scale(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = this.getContext();
h = new Handler();
mCalendarDbHelper=new CalendarDbAdapter(mContext);
mCalendarDbHelper.open();
Cursor thoughts = mCalendarDbHelper.fetchThoughts();
//create a string array of negative thoughts from the db
while (thoughts.moveToNext())
{
if (thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)).length() > 0 && thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)).charAt(0) == '-')
{
negative_thoughts.add(thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)));
}
}
thoughts.close();
array_size = negative_thoughts.size();
mBag =BitmapFactory.decodeResource(getResources(), R.drawable.bag);
mGreenBag = BitmapFactory.decodeResource(getResources(), R.drawable.green_bag);
for (int i = 0; i < 72; i ++)
{
try
{
mScale[i] = BitmapFactory.decodeStream(context.getAssets().open("scale_"+i+".gif"));
}
catch (IOException e)
{
}
}
}
private Runnable r= new Runnable()
{
#Override
public void run() {
invalidate();
}
};
protected void onDraw (Canvas canvas)
{
if (first == true)
{
width = this.getWidth();
height = this.getHeight();
mScale[i] = Bitmap.createScaledBitmap(mScale[i], (int) (width * 1.5), height, true);
mBag = Bitmap.createScaledBitmap(mBag, width/2, height/2, true);
negative = new TextView(mContext);
word = negative_thoughts.get((int) (Math.random() * array_size));
negative.setText(word);
negative.layout(0, 0, width/3, height/4);
negative.setGravity(Gravity.CENTER);
negative.setTextSize(15);
negative.setTextColor(Color.BLACK);
negative.setTypeface(Typeface.DEFAULT_BOLD);
negative.setShadowLayer(5, 2, 2, Color.WHITE);
negative.setDrawingCacheEnabled(true);
negative.setBackgroundResource(R.drawable.graycloud);
positive_paint.setColor(Color.parseColor("#FF4444"));
positive_paint.setShadowLayer(5, 2, 2, Color.YELLOW);
positive_paint.setTypeface(Typeface.DEFAULT_BOLD);
positive_paint.setTextSize(25);
mCurrentXPos[0] = (width/2);
mCurrentYPos[0] = height/4;
mCurrentXPos[1] = (width/2) + (width/8);
mCurrentYPos[1] = height/6;
mCurrentXPos[2] = width/2;
mCurrentYPos[2] = height/12;
mCurrentXPos[3] = (width/2) + (width/8);
mCurrentYPos[3] = height/18;
mMoveXPos[0] = ((width/2) - width)/FRAME_RATE;
mMoveYPos[0] = ((height/4) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[1] = (((width/2) + (width/8)) - width)/ FRAME_RATE;
mMoveYPos[1] = ((height/6) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[2] = ((width/2) - width)/ FRAME_RATE;
mMoveYPos[2] = ((height/12) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[3] = (((width/2) + (width/8)) - width)/ FRAME_RATE;
mMoveYPos[3] = ((height/18) - (height + (height/4)))/FRAME_RATE;
mMoveByXPos[0] = -(width/2)/ FRAME_RATE;
mMoveByYPos[0] = -(height/4)/FRAME_RATE;
mMoveByXPos[1] = ((width - (width/3)) - (width/2 + (width/8)))/ FRAME_RATE;
mMoveByYPos[1] = -(height/6)/FRAME_RATE;
mMoveByXPos[2] = - (width/2)/ FRAME_RATE;
mMoveByYPos[2] = ((height) - (height/12))/FRAME_RATE;
mMoveByXPos[3] = ((width - (width/3)) - (width/2 + (width/8)))/ FRAME_RATE;
mMoveByYPos[3] = ((height) - (height/18))/FRAME_RATE;
currentX = width;
currentY = height + height/4;
first = false;
}
if (game_over == false)
{
canvas.drawBitmap(mScale[i], 0 - (width/4), 0, null);
canvas.drawBitmap(negative.getDrawingCache(),(int) (width/12), (int) (height - (height)/2.5) - (j), null);
}
else
{
canvas.drawBitmap(mBag, width/4, height/4, null);
}
if (mMoveScale == true)
{
i++;
j+=3;
ScaleIt(canvas, i);
if (i == 21 || i == 37 || i == 53 || i == 71)
{
mMoveScale = false;
}
}
if (tracker > 0)
{
if (tracker == 1)
{
if (currentX > width/2 && currentY > height/4 && sStop == false)
{
currentX += mMoveXPos[0];
currentY += mMoveYPos[0];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 2)
{
if (currentX > width/2 + (width/8) && currentY > (height/6) && sStop == false)
{
currentX += mMoveXPos[1];
currentY += mMoveYPos[1];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 3)
{
if (currentX > width/2 && currentY > height/12 && sStop == false)
{
currentX += mMoveXPos[2];
currentY += mMoveYPos[2];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 4)
{
if (currentX > width/2 + (width/8) && currentY > (height/18) && sStop == false)
{
currentX += mMoveXPos[3];
currentY += mMoveYPos[3];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
game_over = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (draw_em > 0 && game_over == false)
{
for (int i = 0; i < draw_em; i ++)
{
if (i == 0)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2, height/4 + j, null);
}
if (i == 1)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2 + (width/8), height/6 + j, null);
}
if (i == 2)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2, height/12 + j, null);
}
if (i == 3)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2 + (width/8), height/18 + j, null);
}
}
}
else if (game_over == true)
{
for (int i = 0; i < draw_em; i++)
{
if (i == 0 && mCurrentXPos[0] > 0 && mCurrentYPos[0] > 0 && mDrag == false)
{
mCurrentXPos[0] += mMoveByXPos[0];
mCurrentYPos[0] += mMoveByYPos[0];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[0], mCurrentYPos[0], null);
}
else if (i == 0 && mCurrentXPos[0] <= 0 || mCurrentYPos[0] <= 0 && mDrag == false)
{
canvas.drawBitmap(mPositive.get(0).getDrawingCache(), 0, 0, null);
}
else if (i == 0 && mDrag == true)
{
canvas.drawBitmap(mPositive.get(0).getDrawingCache(), mCurrentXPos[0], mCurrentYPos[0], null);
}
if (i == 1 && mCurrentXPos[1] < (width - (mPositive.get(i).getWidth()/2)) && mCurrentYPos[1] > mPositive.get(i).getHeight()/2)
{
mCurrentXPos[1] += mMoveByXPos[1];
mCurrentYPos[1] += mMoveByYPos[1];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[1], mCurrentYPos[1], null);
}
else if (i == 1 && mCurrentXPos[1] >= (width - (mPositive.get(i).getWidth()/2)) || mCurrentYPos[1] <= mPositive.get(i).getHeight()/2)
{
canvas.drawBitmap(mPositive.get(1).getDrawingCache(), width - (width/3), 0, null);
}
if (i == 2 && mCurrentXPos[2] > (mPositive.get(i).getWidth()/2) && mCurrentYPos[2] < (height - mPositive.get(i).getHeight()/2))
{
mCurrentXPos[2] += mMoveByXPos[2];
mCurrentYPos[2] += mMoveByYPos[2];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[2], mCurrentYPos[2], null);
}
else if (i == 2 && mCurrentXPos[2] <= (mPositive.get(i).getWidth()/2) || mCurrentYPos[2] >= (height - mPositive.get(i).getHeight()/2))
{
canvas.drawBitmap(mPositive.get(2).getDrawingCache(), 0, height - (height/4), null);
}
if (i == 3 && mCurrentXPos[3] < (width - (mPositive.get(i).getWidth()/2)) && mCurrentYPos[3] < (height - mPositive.get(i).getHeight()/2))
{
mCurrentXPos[3] += mMoveByXPos[3];
mCurrentYPos[3] += mMoveByYPos[3];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[3], mCurrentYPos[3], null);
}
else if (i == 3 && mCurrentXPos[3] >= (width - (mPositive.get(i).getWidth()/2)) || mCurrentYPos[3] >= (height - mPositive.get(i).getHeight()/2))
{
canvas.drawBitmap(mPositive.get(3).getDrawingCache(), width - (width/3), height - (height/4), null);
}
}
}
}
h.postDelayed(r, FRAME_RATE);
}
protected void moveIt(Canvas canvas, int moveX,int moveY, int i)
{
if (i == 0)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 1)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 2)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 3)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
}
protected void moveEm(Canvas canvas, int[]mMovePosX, int[] mMovePosY)
{
for (int i = 0; i < 4; i++)
{
}
}
protected void ScaleIt(Canvas canvas, int i)
{
mScale[i] = Bitmap.createScaledBitmap(mScale[i], (int) (width * 1.5), height, true);
mScale[i-1].recycle();
}
}
And here is the activity:
public class ScaleView extends Activity
{
Context mContext;
Scale mScale;
EditText positive_thought;
Button fire;
TextView pos;
private static Set<String> mPositiveWords;
private static Set<String> mNegativeWords;
int count;
private Pattern four_letter_words = Pattern.compile("not|cant|cnt|can't");
String inputLine;
private String[] inputTokens;
Button question;
Button skip;
public static boolean populatePositiveWords(Context context)
{
mNegativeWords = new HashSet<String>();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open("negative_words.txt")));
String line = reader.readLine();
while (line != null)
{
mNegativeWords.add(line.toLowerCase(Locale.US));
line = reader.readLine();
}
reader.close();
}
catch (IOException exception)
{
return false;
}
return true;
//TODO list of negative words
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getActionBar().hide();
mContext = this;
populatePositiveWords(mContext);
setContentView(R.layout.activity_scale);
mScale = (Scale) findViewById(R.id.anim_view);
mScale.setClickable(true);
positive_thought = (EditText) findViewById(R.id.thoughts);
fire = (Button) findViewById(R.id.scale_it);
skip = (Button) findViewById(R.id.skip);
question = (Button) findViewById(R.id.question);
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(60);
positive_thought.setFilters(FilterArray);
fire.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
//if the button is clicked invalidate the ondraw method and pass in the text of the positive word
inputLine = positive_thought.getText().toString();
inputTokens = inputLine.split(" ");
if (inputLine.isEmpty())
{
Toast.makeText(mContext, "You have to write something!", Toast.LENGTH_SHORT).show();
return;
}
if (inputTokens.length < 3)
{
Toast.makeText(mContext, "At least three words are required.", Toast.LENGTH_SHORT).show();
return;
}
if (four_letter_words.matcher(inputLine).find() == true)
{
Toast.makeText(mContext, "Make an affirmative statement!", Toast.LENGTH_SHORT).show();
return;
}
boolean matchesToken = false;
for (int i = 0; i < inputTokens.length; i++)
{
String token = inputTokens[i];
if (mNegativeWords.contains(token.toLowerCase(Locale.US)))
{
matchesToken = true;
break;
}
}
if (matchesToken == true)
{
Toast.makeText(mContext, "Use positive words!", Toast.LENGTH_SHORT).show();
return;
}
else
{
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(positive_thought.getWindowToken(), 0);
pos = new TextView (mContext);
pos.layout(0, 0, mScale.width/3, mScale.height/4);
pos.setGravity(Gravity.CENTER);
pos.setTextSize(15);
pos.setTextColor(Color.RED);
pos.setTypeface(Typeface.DEFAULT_BOLD);
pos.setShadowLayer(5, 2, 2, Color.YELLOW);
pos.setText(positive_thought.getText().toString());
pos.setDrawingCacheEnabled(true);
pos.setBackgroundResource(R.drawable.whitecloud);
pos.setClickable(true);
mScale.mPositive.add(pos);
mScale.scale_it = true;
count++;
mScale.sStop = false;
mScale.tracker = count;
if (count == 4)
{
((RelativeLayout)question.getParent()).removeView(question);
((RelativeLayout)skip.getParent()).removeView(skip);
mScale.mPositive.get(0).setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScale.mCurrentXPos[0] = event.getX();
mScale.mCurrentYPos[0] = event.getY();
mScale.mDrag = true;
return true;
}
});
}
}
positive_thought.setText(null);
}
});
}
}
The reason your TextView cannot receive touch events is that the TextView is drawn on the canvas just as a bitmap, not as a View. An excerpt from your code shown below illustrates this.
protected void onDraw(Canvas canvs)
{
....
negative = new TextView(mContext);
...
canvas.drawBitmap(negative.getDrawingCache(), ...)
To deliver touch events to your TextView, your Scale class should extend not View but ViewGroup and the TextView needs to be added as a subview to Scale class by using ViewGroup.addView() or addViewInLayout(). It is not a simple task to implement a ViewGroup subclass. You may have to implement onInterceptTouchEvent(MotionEvent) depending on your needs.
Android's source code will be of help.
Is your CustomView also sets some TouchListner??
If yes then this might causing issue..Remove TouchListner from CustomView and see if it works..
Here is the image URL for the alphabetical list view. I couldn't post it here as stackoverflow restricts me not having more reputations.
http://www.freeimagehosting.net/hwg9g
How to show this alphabetical scrollview in the left side of the screen. I have got a sample application from internet for alphabetical scrollview and i have implemented with my project :-( As a beginner i do not understand their way of coding. They have used drawRoundRect method to draw this. I regret drawRoundRect and some paint stuffs are not familiar to me..!
public class IndexScroller {
private float mIndexbarWidth;
private float mIndexbarMargin;
private float mPreviewPadding;
private float mDensity;
private float mScaledDensity;
private float mAlphaRate;
private int mState = STATE_HIDDEN;
private int mListViewWidth;
private int mListViewHeight;
private int mCurrentSection = -1;
private boolean mIsIndexing = false;
private ListView mListView = null;
private SectionIndexer mIndexer = null;
private String[] mSections = null;
private RectF mIndexbarRect;
private static final int STATE_HIDDEN = 0;
private static final int STATE_SHOWING = 1;
private static final int STATE_SHOWN = 2;
private static final int STATE_HIDING = 3;
public IndexScroller(Context context, ListView lv) {
mDensity = context.getResources().getDisplayMetrics().density;
mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mListView = lv;
setAdapter(mListView.getAdapter());
mIndexbarWidth = 20 * mDensity;
mIndexbarMargin = 10 * mDensity;
mPreviewPadding = 5 * mDensity;
}
public void draw(Canvas canvas) {
if (mState == STATE_HIDDEN)
return;
// mAlphaRate determines the rate of opacity
Paint indexbarPaint = new Paint();
indexbarPaint.setColor(Color.BLACK);
indexbarPaint.setAlpha((int) (64 * mAlphaRate));
indexbarPaint.setAntiAlias(true);
canvas.drawRoundRect(mIndexbarRect, 5 * mDensity, 5 * mDensity,
indexbarPaint);
if (mSections != null && mSections.length > 0) {
// Preview is shown when mCurrentSection is set
if (mCurrentSection >= 0) {
Paint previewPaint = new Paint();
previewPaint.setColor(Color.BLACK);
previewPaint.setAlpha(96);
previewPaint.setAntiAlias(true);
previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(50 * mScaledDensity);
float previewTextWidth = previewTextPaint
.measureText(mSections[mCurrentSection]);
float previewSize = 2 * mPreviewPadding
+ previewTextPaint.descent()
- previewTextPaint.ascent();
RectF previewRect = new RectF(
(mListViewWidth - previewSize) / 2,
(mListViewHeight - previewSize) / 2,
(mListViewWidth - previewSize) / 2 + previewSize,
(mListViewHeight - previewSize) / 2 + previewSize);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity,
previewPaint);
canvas.drawText(
mSections[mCurrentSection],
previewRect.left + (previewSize - previewTextWidth) / 2
- 1,
previewRect.top + mPreviewPadding
- previewTextPaint.ascent() + 1,
previewTextPaint);
}
Paint indexPaint = new Paint();
indexPaint.setColor(Color.WHITE);
indexPaint.setAlpha((int) (255 * mAlphaRate));
indexPaint.setAntiAlias(true);
indexPaint.setTextSize(12 * mScaledDensity);
float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin)
/ mSections.length;
float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint
.ascent())) / 2;
for (int i = 0; i < mSections.length; i++) {
float paddingLeft = (mIndexbarWidth - indexPaint
.measureText(mSections[i])) / 2;
canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft,
mIndexbarRect.top + mIndexbarMargin + sectionHeight * i
+ paddingTop - indexPaint.ascent(), indexPaint);
}
}
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// If down event occurs inside index bar region, start indexing
if (mState != STATE_HIDDEN && contains(ev.getX(), ev.getY())) {
setState(STATE_SHOWN);
// It demonstrates that the motion event started from index bar
mIsIndexing = true;
// Determine which section the point is in, and move the list to
// that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer
.getPositionForSection(mCurrentSection));
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if (mIsIndexing) {
// If this event moves inside index bar
if (contains(ev.getX(), ev.getY())) {
// Determine which section the point is in, and move the
// list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer
.getPositionForSection(mCurrentSection));
}
return true;
}
break;
case MotionEvent.ACTION_UP:
if (mIsIndexing) {
mIsIndexing = false;
mCurrentSection = -1;
}
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
break;
}
return false;
}
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(w - mIndexbarMargin - mIndexbarWidth,
mIndexbarMargin, w - mIndexbarMargin, h - mIndexbarMargin);
}
public void show() {
if (mState == STATE_HIDDEN)
setState(STATE_SHOWING);
else if (mState == STATE_HIDING)
setState(STATE_HIDING);
}
public void hide() {
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
}
public void setAdapter(Adapter adapter) {
if (adapter instanceof SectionIndexer) {
mIndexer = (SectionIndexer) adapter;
mSections = (String[]) mIndexer.getSections();
}
}
private void setState(int state) {
if (state < STATE_HIDDEN || state > STATE_HIDING)
return;
mState = state;
switch (mState) {
case STATE_HIDDEN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_SHOWING:
// Start to fade in
mAlphaRate = 0;
fade(0);
break;
case STATE_SHOWN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_HIDING:
// Start to fade out after three seconds
mAlphaRate = 1;
fade(5000);
break;
}
}
private boolean contains(float x, float y) {
// Determine if the point is in index bar region, which includes the
// right margin of the bar
return (x >= mIndexbarRect.left && y >= mIndexbarRect.top && y <= mIndexbarRect.top
+ mIndexbarRect.height());
}
private int getSectionByPoint(float y) {
if (mSections == null || mSections.length == 0)
return 0;
if (y < mIndexbarRect.top + mIndexbarMargin)
return 0;
if (y >= mIndexbarRect.top + mIndexbarRect.height() - mIndexbarMargin)
return mSections.length - 1;
return (int) ((y - mIndexbarRect.top - mIndexbarMargin) / ((mIndexbarRect
.height() - 2 * mIndexbarMargin) / mSections.length));
}
private void fade(long delay) {
mHandler.removeMessages(0);
mHandler.sendEmptyMessageAtTime(0, SystemClock.uptimeMillis() + delay);
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (mState) {
case STATE_SHOWING:
// Fade in effect
mAlphaRate += (1 - mAlphaRate) * 0.2;
if (mAlphaRate > 0.9) {
mAlphaRate = 1;
setState(STATE_SHOWN);
}
mListView.invalidate();
fade(10);
break;
case STATE_SHOWN:
// If no action, hide automatically
setState(STATE_HIDING);
break;
case STATE_HIDING:
// Fade out effect
mAlphaRate -= mAlphaRate * 0.2;
if (mAlphaRate < 0.1) {
mAlphaRate = 0;
setState(STATE_HIDDEN);
}
mListView.invalidate();
fade(10);
break;
}
}
};
It would be really nice if you help me to show this alphabetical scroll bar in the left side of the screen.
I got that this way,
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(mIndexbarMargin, mIndexbarMargin,
mIndexbarMargin + mIndexbarWidth, h - mIndexbarMargin);
}
This is the method to draw the rectangle in left side of the screen.
private boolean contains(float x, float y) {
return (x <= mIndexbarRect.right && y >= mIndexbarRect.top && y <= mIndexbarRect.top
+ mIndexbarRect.height());
}
It will work smoothly if you change the function to the below. sorry for the posting this answer little late.
please check out : Indexable list view