how to check what Path was clicked in canvas android studio? - android

I'm doing a Canvas to draw a squares on a board in Canvas in Android Studio,
I need to know what path was clicked in my onTouchEvent
but all i can take out from there is an event.x and event.y,
because I have a pretty complicated shape it will be very hard to calculate only based on x and y what path was clicked.
Is there another way I can check the clicked path on the screen ?
Here is my canvas:
public class PianoKeysWidget extends View {
public class ChessSlice extends Path {
public ChessSlice() {
key = "C";
octave = 0;
isKeyBlack = false;
}
public String key;
public int octave;
public boolean isKeyBlack;
}
Paint WhiteKeyPaint, BlackKeyPaint, OuterRimPaint;
Boolean isTouching = false;
float touchY, touchX;
int globalKeyWidth = 20;
PianoKeysInterface mainInterface;
ChessSlice framePath;
ArrayList<ChessSlice> pianoPathsArray = new ArrayList<ChessSlice>();
int width = 340; // default numbers until the screen will change it when it gets the actuall view
int height = 1200; // default numbers until the screen will change it when it gets the actuall view
String TAG = "alignmentWidget";
/**
* construuctor
*
* #param context
*/
public PianoKeysWidget(Context context) {
super(context);
this.postInvalidate();
init();
}
/**
* constructor
*
* #param context
* #param attrs
*/
public PianoKeysWidget(Context context, AttributeSet attrs) {
super(context, attrs);
this.postInvalidate();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = getWidth();
height = getHeight();
init();
}
/**
* constructor
*
* #param context
* #param attrs
* #param defStyleAttr
*/
public PianoKeysWidget(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.postInvalidate();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
private static Bitmap getBitmap(Context context, int drawableId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return BitmapFactory.decodeResource(context.getResources(), drawableId);
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
//////////////////////////////////
//////////////On Draw//////////////
//////////////////////////////////
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap bitmap = getBitmap(getContext(), R.drawable.ic_accessibility_black_24dp);
if (pianoPathsArray.size() == 0) { // initlizes the init
init();
}
// draws the first circle
////////////////////////////////////////////
//go through the array and paints the corisponding cells
///////////////////////////////////////////
for (int i = 0; i < pianoPathsArray.size(); i++) {
canvas.drawPath(pianoPathsArray.get(i), WhiteKeyPaint);
if (pianoPathsArray.get(i).isKeyBlack) {
canvas.drawPath(pianoPathsArray.get(i), BlackKeyPaint);
}
canvas.drawPath(pianoPathsArray.get(i), OuterRimPaint);
// if (pianoPathsArray.get(i).color.equals("white")) {
// canvas.drawPath(pianoPathsArray.get(i), WhiteKeyPaint);
// } else {
// canvas.drawPath(pianoPathsArray.get(i), BlackKeyPaint);
// }
//
//
//
// //draw the queens
// if (pianoPathsArray.get(i).isOcupied) {
// canvas.drawBitmap(bitmap, pianoPathsArray.get(i).centerX - 40, pianoPathsArray.get(i).centerY - 45, BlackKeyPaint);
// }
}
//draw the frame
canvas.drawPath(framePath, OuterRimPaint);
}
private void activateErrorAnimationTimer(final ChessSlice chessSlice) {
}
private void init() {
if (pianoPathsArray.size() > 0) { // initlizes the init
return;
}
//gets teh width and height, initlized only after ondraw happend so it wouldn't be 0 0
width = getWidth();
height = getHeight();
//defining paints
///////////////////////////////////////////
WhiteKeyPaint = new Paint();
WhiteKeyPaint.setColor(getResources().getColor(R.color.lightKeyColor));
WhiteKeyPaint.setStyle(Paint.Style.FILL_AND_STROKE);
BlackKeyPaint = new Paint();
BlackKeyPaint.setColor(getResources().getColor(R.color.darkKeyColor));
BlackKeyPaint.setStyle(Paint.Style.FILL_AND_STROKE);
OuterRimPaint = new Paint();
OuterRimPaint.setStrokeWidth(10f);
OuterRimPaint.setColor(getResources().getColor(R.color.colorAccent));
OuterRimPaint.setStyle(Paint.Style.STROKE);
// applyes hardware Acceleration
///////////////////////////////////////////
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(LAYER_TYPE_SOFTWARE, BlackKeyPaint);
}
int overAllKeys = Globals.getInstance().numberOfPianoKeys;
int numberWhiteKeys = getWhiteKeysCount(overAllKeys)-1;
int numberBlackKeys = getBlackKeysCount(overAllKeys);
Log.d ("testings", "whitekeys: "+numberWhiteKeys);
Log.d ("testings", "blackKeys: "+numberBlackKeys);
// gets the main slices paths
///////////////////////////////////////////
for (int i = 0; i <= numberWhiteKeys; i++) {
pianoPathsArray.add(getSlicesPathsWhite(i, numberWhiteKeys));
}
for (int i = 0; i <= numberBlackKeys; i++) {
pianoPathsArray.add(getSlicesPathsBlack(i, numberBlackKeys, numberWhiteKeys));
}
//draw frame
framePath = new ChessSlice();
framePath.moveTo(0, 0);
framePath.lineTo(width, 0);
framePath.lineTo(width, height);
framePath.lineTo(0, height);
framePath.lineTo(0, 0);
}
private int getBlackKeysCount(int overAllKeys) {
int allKeys = overAllKeys;
int blackKeys = 0;
while (allKeys > 12) {
blackKeys = blackKeys + 5;
allKeys = allKeys - 12;
}
if (allKeys == 12) {
blackKeys = blackKeys + 5;
} else if (allKeys == 11) {
blackKeys = blackKeys + 5;
} else if (allKeys == 10) {
blackKeys = blackKeys + 4;
}else if (allKeys == 9) {
blackKeys = blackKeys + 4;
}else if (allKeys == 8) {
blackKeys = blackKeys + 3;
}else if (allKeys == 7) {
blackKeys = blackKeys + 3;
}else if (allKeys == 6) {
blackKeys = blackKeys + 2;
}else if (allKeys == 5) {
blackKeys = blackKeys + 2;
}else if (allKeys == 4) {
blackKeys = blackKeys + 2;
}else if (allKeys == 3) {
blackKeys = blackKeys + 1;
}else if (allKeys == 2) {
blackKeys = blackKeys + 1;
}else if (allKeys == 1) {
blackKeys = blackKeys + 0;
}
return blackKeys;
}
private int getWhiteKeysCount(int overAllKeys) {
int allKeys = overAllKeys;
int whiteKeys = 0;
while (allKeys > 12) {
whiteKeys = whiteKeys + 7;
allKeys = allKeys - 12;
}
if (allKeys == 12) {
whiteKeys = whiteKeys + 8;
} else if (allKeys == 11) {
whiteKeys = whiteKeys + 7;
} else if (allKeys == 10) {
whiteKeys = whiteKeys + 6;
}else if (allKeys == 9) {
whiteKeys = whiteKeys + 6;
}else if (allKeys == 8) {
whiteKeys = whiteKeys + 5;
}else if (allKeys == 7) {
whiteKeys = whiteKeys + 5;
}else if (allKeys == 6) {
whiteKeys = whiteKeys + 4;
}else if (allKeys == 5) {
whiteKeys = whiteKeys + 3;
}else if (allKeys == 4) {
whiteKeys = whiteKeys + 2;
}else if (allKeys == 3) {
whiteKeys = whiteKeys + 2;
}else if (allKeys == 2) {
whiteKeys = whiteKeys + 1;
}else if (allKeys == 1) {
whiteKeys = whiteKeys + 1;
}
return whiteKeys;
}
public ChessSlice getSlicesPathsWhite(int i, int numberWhiteKeys) {
int KeyWidth = width / numberWhiteKeys;
int rowHeight = height;
int startX = 0+(i*KeyWidth);
int startY = 0;
ChessSlice segmentPath = new ChessSlice();
segmentPath.moveTo(startX, startY);
segmentPath.lineTo(startX+KeyWidth, startY);
segmentPath.lineTo(startX+KeyWidth, startY+rowHeight);
segmentPath.lineTo(startX, startY+rowHeight);
segmentPath.lineTo(startX, startY);
segmentPath.key = getCorrectKeyForNumber(i);
segmentPath.octave = getCorrectOctavForNumber(i);
segmentPath.isKeyBlack = false;
return segmentPath;
}
public ChessSlice getSlicesPathsBlack(int i, int numberBlackeys, int numberWhiteKeys) {
int KeyWidth = width / numberWhiteKeys;
int rowHeight = height/2;
int modifierForBlackKeys = getBlackKeyModifier(i);
int startX = (KeyWidth/2)+(i*KeyWidth)+(modifierForBlackKeys*KeyWidth);
int startY = 0;
ChessSlice segmentPath = new ChessSlice();
segmentPath.moveTo(startX, startY);
segmentPath.lineTo(startX+KeyWidth, startY);
segmentPath.lineTo(startX+KeyWidth, startY+rowHeight);
segmentPath.lineTo(startX, startY+rowHeight);
segmentPath.lineTo(startX, startY);
segmentPath.key = getCorrectBlackKeyForNumber(i);
segmentPath.octave = getCorrectBlackOctavForNumber(i);
segmentPath.isKeyBlack = true;
return segmentPath;
}
private int getBlackKeyModifier(int i) {
int modifier = 0;
if (i >= 10) {
modifier = 4;
}else if (i >= 7) {
modifier = 3;
} else if (i >= 5) {
modifier = 2;
} else if (i >= 2) {
modifier = 1;
}
return modifier;
}
private String getCorrectKeyForNumber (int number) {
int functionNum = number;
String key = "C";
while (functionNum > 6) {
functionNum = functionNum - 7;
}
if (functionNum == 0) {
key = "C";
}else if (functionNum == 1) {
key = "D";
}else if (functionNum == 2) {
key = "E";
}else if (functionNum == 3) {
key = "F";
}else if (functionNum == 4) {
key = "G";
}else if (functionNum == 5) {
key = "A";
}else if (functionNum == 6) {
key = "B";
}
return key;
}
private String getCorrectBlackKeyForNumber (int number) {
int functionNum = number;
String key = "C#";
while (functionNum > 4) {
functionNum = functionNum - 5;
}
if (functionNum == 0) {
key = "C#";
}else if (functionNum == 1) {
key = "D#";
}else if (functionNum == 2) {
key = "F#";
}else if (functionNum == 3) {
key = "G#";
}else if (functionNum == 4) {
key = "A#";
}
return key;
}
private int getCorrectOctavForNumber (int number) {
int functionNum = number;
int octave = 0;
while (functionNum > 6) {
octave = octave + 1;
functionNum = functionNum - 7;
}
return octave;
}
private int getCorrectBlackOctavForNumber (int number) {
int functionNum = number;
int octave = 0;
while (functionNum > 4) {
octave = octave + 1;
functionNum = functionNum - 5;
}
return octave;
}
// private TouchModel calculateTouchKey (Float touchX, Float touchY) {
//
// int columWidth = width/COLUMS_COUNT;
// int rowHeight = height/ROWS_COUNT;
//
// int selectectColum = (int) Math.floor(touchX/columWidth)+1;
// int selectectRow = (int) Math.floor(touchY/rowHeight)+1;
//
// TouchModel touchModel = new TouchModel(selectectColum, selectectRow);
//
//
// mainInterface.widgetTouched(selectectColum, selectectRow);
//
// return touchModel;
// }
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
isTouching = true;
// Log.d ("Testings", "Touch Event: "+event);
// calculateTouchKey(touchX, touchY);
// Log.d (TAG, "touched: "+touchX+" and: "+touchY);
// Log.d (TAG, "x: "+selectedCells.touchX+" y: "+selectedCells.touchY);
break;
default:
isTouching = false;
}
invalidate();
return true;
}
public void initlizeWidgetVars (PianoKeysInterface chessBoardInterface) {
mainInterface = chessBoardInterface;
mainInterface.setChessArray(pianoPathsArray);
}
public void updateChessArray(ArrayList<ChessSlice> localChessArray) {
pianoPathsArray = localChessArray;
this.postInvalidate();
}
}

fixed it by :
for (int i = 0; i < pianoPathsArray.size(); i++) {
RectF boundrySlice=new RectF();
pianoPathsArray.get(i).computeBounds(boundrySlice, true);
if(boundrySlice.contains(touchX,touchY)){
selectedPath= pianoPathsArray.get(i);// where selectedPath is declared Globally.
}
}

Related

Custom Recyclerview layoutmanager scroll to position issue

I'm Having a design where I need to show like this:
I am finished with all changes but I need to scroll to the position I clicked and it's not working
public class CircularLayoutManager extends LinearLayoutManager {
private static final int CIRCLE = 0;
private static final int ELLIPSE = 1;
private static final int MILLISECONDS_PER_INCH = 30;
private RecyclerView recyclerView;
private Rect recyclerBounds;
private int topOfFirstChild;
private Rect childDecoratedBoundsWithMargin;
private int verticalCenter;
private boolean scrolled;
private float radius;
private float majorRadius, minorRadius;
private float centerX;
private #LayoutPath int layoutPath;
#IntDef({CIRCLE, ELLIPSE})
#interface LayoutPath {
}
public CircularLayoutManager(Context context, int radius, int centerX) {
super(context);
this.radius = Utils.dpToPx(context, radius);
this.centerX = Utils.dpToPx(context, centerX);
layoutPath = ELLIPSE;
}
public CircularLayoutManager(Context context, int majorRadius, int minorRadius, int centerX) {
super(context);
this.majorRadius = Utils.dpToPx(context, majorRadius);
this.minorRadius = Utils.dpToPx(context, minorRadius);
this.centerX = Utils.dpToPx(context, centerX);
layoutPath = ELLIPSE;
}
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getItemCount() == 0) {
detachAndScrapAttachedViews(recycler);
return;
}
if (recyclerBounds == null) {
recyclerBounds = new Rect();
recyclerView.getHitRect(recyclerBounds);
verticalCenter = (recyclerBounds.height() / 2);
}
if (getChildCount() == 0) {
fill(0, recycler);
}
}
private void fill(int indexToStartFill, RecyclerView.Recycler recycler) {
if (indexToStartFill < 0) {
indexToStartFill = 0;
}
int childTop = topOfFirstChild;
detachAndScrapAttachedViews(recycler);
for (int i = indexToStartFill; i < getItemCount(); i++) {
View child = recycler.getViewForPosition(i);
measureChildWithMargins(child, 0, 0);
int sumOfHorizontalMargins = ((RecyclerView.LayoutParams) child.getLayoutParams()).leftMargin
+ ((RecyclerView.LayoutParams) child.getLayoutParams()).rightMargin;
int sumOfVerticalMargins = ((RecyclerView.LayoutParams) child.getLayoutParams()).topMargin
+ ((RecyclerView.LayoutParams) child.getLayoutParams()).bottomMargin;
int childLeft = 0;
switch (layoutPath) {
case CIRCLE:
childLeft = calculateCircleXFromY(childTop + (getDecoratedMeasuredHeight(child) +
getTopDecorationHeight(child) - getBottomDecorationHeight(child) + sumOfVerticalMargins) / 2);
break;
case ELLIPSE:
childLeft = calculateEllipseXFromY(childTop + (getDecoratedMeasuredHeight(child) +
getTopDecorationHeight(child) - getBottomDecorationHeight(child) + sumOfVerticalMargins) / 2);
break;
}
if (!(recyclerBounds.intersects(recyclerBounds.left + childLeft, recyclerBounds.top + childTop,
recyclerBounds.left + childLeft + getDecoratedMeasuredWidth(child) + sumOfHorizontalMargins,
recyclerBounds.top + childTop + getDecoratedMeasuredHeight(child) + sumOfVerticalMargins)
|| recyclerBounds.contains(recyclerBounds.left + childLeft, recyclerBounds.top + childTop,
recyclerBounds.left + childLeft + getDecoratedMeasuredWidth(child) + sumOfHorizontalMargins,
recyclerBounds.top + childTop + getDecoratedMeasuredHeight(child) + sumOfVerticalMargins))) {
break;
}
addView(child);
layoutDecoratedWithMargins(child, childLeft, childTop, childLeft + getDecoratedMeasuredWidth(child)
+ sumOfHorizontalMargins, childTop + getDecoratedMeasuredHeight(child) + sumOfVerticalMargins);
getDecoratedBoundsWithMargins(child, childDecoratedBoundsWithMargin);
scaleChild(child);
childTop += childDecoratedBoundsWithMargin.height();
}
List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList();
for (int i = 0; i < scrapList.size(); i++) {
View viewRemoved = scrapList.get(i).itemView;
recycler.recycleView(viewRemoved);
}
if (!scrolled) {
stabilize();
}
}
#Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (!scrolled) {
scrolled = true;
}
int delta = dy;
if (delta > 50) {
delta = 50;
}
if (delta < -50) {
delta = -50;
}
if (getChildCount() == 0) {
return dy;
}
System.out.println("Dy:"+dy);
if (getPosition(getChildAt(getChildCount() - 1)) == getItemCount() - 1) {
View child = getChildAt(getChildCount() - 1); getDecoratedBoundsWithMargins(child, childDecoratedBoundsWithMargin);
if (childDecoratedBoundsWithMargin.bottom - delta < recyclerBounds.height()) {
int position = recyclerBounds.height();
int indexToStartFill = getPosition(getChildAt(0));
for (int i = getChildCount() - 1; i >= 0; i--) {
getDecoratedBoundsWithMargins(getChildAt(i), childDecoratedBoundsWithMargin);
position -= childDecoratedBoundsWithMargin.height();
if (position <= 0) {
topOfFirstChild = position;
if (topOfFirstChild <= -childDecoratedBoundsWithMargin.height()) {
topOfFirstChild += childDecoratedBoundsWithMargin.height();
}
indexToStartFill = getPosition(getChildAt(i));
if (indexToStartFill >= getItemCount()) {
indexToStartFill = getItemCount() - 1;
}
break;
}
}
fill(indexToStartFill, recycler);
return 0;
}
}
topOfFirstChild -= delta;
getDecoratedBoundsWithMargins(getChildAt(0), childDecoratedBoundsWithMargin);
int indexToStartFill = getPosition(getChildAt(0));
if (topOfFirstChild > 0) {
topOfFirstChild -= childDecoratedBoundsWithMargin.height();
indexToStartFill--;
if (indexToStartFill == -1) {
topOfFirstChild = 0;
fill(0, recycler);
return 0;
}
} else if (topOfFirstChild <= -childDecoratedBoundsWithMargin.height()) {
topOfFirstChild += childDecoratedBoundsWithMargin.height();
indexToStartFill++;
}
fill(indexToStartFill, recycler);
return dy;
}
}
And main content like this:
recyclerView.setAdapter(new RecyclerViewAdapter(getApplicationContext(), list));
recyclerView.addItemDecoration(new RecyclerItemDecoration());
layoutManager = new CircularLayoutManager(getApplicationContext(), 350, 0);
recyclerView.setLayoutManager(layoutManager);
Full Source Code
I need to remove the top padding at first time loading and when user clicks the list i need to move item to the center.

How to fill the color gradually on drawn view canvas Android

I am having a WaveFormView on which I want to change the color of it while playing Audio file and as the Audio is paused it should be stopped coloring at that certain point and when resumed it should continue forward with coloring. I am not getting how to do it in my code..
This is the screen shot of my generated waveform. Now when I will click on Play button it should change the color of waveform gradually with red color (from start to end slowly).
Here is my code to draw waveform view.
WaveFormView.class
public class WaveformView extends View {
public interface WaveformListener {
public void waveformFling(float x);
public void waveformDraw();
}
;
// Colors
private Paint mGridPaint;
private Paint mSelectedLinePaint;
private Paint mUnselectedLinePaint;
private Paint mUnselectedBkgndLinePaint;
private Paint mBorderLinePaint;
private Paint mPlaybackLinePaint;
private Paint mTimecodePaint;
private SoundFile mSoundFile;
private int[] mLenByZoomLevel;
private double[][] mValuesByZoomLevel;
private double[] mZoomFactorByZoomLevel;
private int[] mHeightsAtThisZoomLevel;
private int mZoomLevel;
private int mNumZoomLevels;
private int mSampleRate;
private int mSamplesPerFrame;
private int mOffset;
private int mSelectionStart;
private int mSelectionEnd;
private int mPlaybackPos;
private float mDensity;
private float mInitialScaleSpan;
private WaveformListener mListener;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleGestureDetector;
private boolean mInitialized;
Color color;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.color.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.color.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.color.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.color.selection_border));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[]{3.0f, 2.0f}, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.color.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.color.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.color.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.color.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
public boolean hasSoundFile() {
return mSoundFile != null;
}
public void setSoundFile(SoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
/**
* Called once when a new sound file is added
*/
private void computeDoublesForAllZoomLevels() {
int numFrames = mSoundFile.getNumFrames();
int[] frameGains = mSoundFile.getFrameGains();
double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (double)(
(frameGains[0] / 2.0) +
(frameGains[1] / 2.0));
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] = (double)(
(frameGains[i - 1] / 3.0) +
(frameGains[i ] / 3.0) +
(frameGains[i + 1] / 3.0));
}
smoothedGains[numFrames - 1] = (double)(
(frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0));
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0)
smoothedGain = 0;
if (smoothedGain > 255)
smoothedGain = 255;
if (smoothedGain > maxGain)
maxGain = smoothedGain;
gainHist[smoothedGain]++;
}
// Re-calibrate the min to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the heights
double[] heights = new double[numFrames];
double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0)
value = 0.0;
if (value > 1.0)
value = 1.0;
heights[i] = value * value;
}
mNumZoomLevels = 5;
mLenByZoomLevel = new int[5];
mZoomFactorByZoomLevel = new double[5];
mValuesByZoomLevel = new double[5][];
// Level 0 is doubled, with interpolated values
mLenByZoomLevel[0] = numFrames * 2;
mZoomFactorByZoomLevel[0] = 2.0;
mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
if (numFrames > 0) {
mValuesByZoomLevel[0][0] = 0.5 * heights[0];
mValuesByZoomLevel[0][1] = heights[0];
}
for (int i = 1; i < numFrames; i++) {
mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
mValuesByZoomLevel[0][2 * i + 1] = heights[i];
}
// Level 1 is normal
mLenByZoomLevel[1] = numFrames;
mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
mZoomFactorByZoomLevel[1] = 1.0;
for (int i = 0; i < mLenByZoomLevel[1]; i++) {
mValuesByZoomLevel[1][i] = heights[i];
}
// 3 more levels are each halved
for (int j = 2; j < 5; j++) {
mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
for (int i = 0; i < mLenByZoomLevel[j]; i++) {
mValuesByZoomLevel[j][i] =
0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
mValuesByZoomLevel[j - 1][2 * i + 1]);
}
}
if (numFrames > 5000) {
mZoomLevel = 3;
} else if (numFrames > 1000) {
mZoomLevel = 2;
} else if (numFrames > 300) {
mZoomLevel = 1;
} else {
mZoomLevel = 0;
}
mInitialized = true;
}
public boolean canZoomIn() {
return (mZoomLevel > 0);
}
public void zoomIn() {
if (canZoomIn()) {
mZoomLevel--;
mSelectionStart *= 2;
mSelectionEnd *= 2;
mHeightsAtThisZoomLevel = null;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter *= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
invalidate();
}
}
public boolean canZoomOut() {
return (mZoomLevel < mNumZoomLevels - 1);
}
public void zoomOut() {
if (canZoomOut()) {
mZoomLevel++;
mSelectionStart /= 2;
mSelectionEnd /= 2;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter /= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
mHeightsAtThisZoomLevel = null;
invalidate();
}
}
public double pixelsToSeconds(int pixels) {
double z = mZoomFactorByZoomLevel[mZoomLevel];
return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
}
public void setListener(WaveformListener listener) {
mListener = listener;
}
public void recomputeHeights(float density) {
mHeightsAtThisZoomLevel = null;
mDensity = density;
mTimecodePaint.setTextSize((int)(12 * density));
invalidate();
}
protected void drawWaveformLine(Canvas canvas,
int x, int y0, int y1,
Paint paint) {
canvas.drawLine(x, y0, x, y1, paint);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
int height = displaymetrics.heightPixels;
int widths = displaymetrics.widthPixels;
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
Log.e("wid",String.valueOf(width));
Log.e("widCal",String.valueOf(mHeightsAtThisZoomLevel.length));
Log.e("widstart",String.valueOf(start));
if (width > measuredWidth)
width = measuredWidth;
Log.e("measured",String.valueOf(measuredWidth));
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for ( i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
// paint.setColor(color);
} else {
drawWaveformLine(canvas, ((widths/width)*i), 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
private void computeIntsForThisZoomLevel() {
int halfHeight = (getMeasuredHeight() / 2) - 1;
mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
mHeightsAtThisZoomLevel[i] =
(int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements WaveformView.WaveformListener {
WaveformView mWaveformView;
SoundFile mSoundFile;
private float mDensity;
private File mFile;
private String mFilename;
private long mLoadingLastUpdateTime;
boolean mLoadingKeepGoing;
boolean mFinishActivity;
private ProgressDialog mProgressDialog;
String mTitle,mArtist;
private Thread mLoadSoundFileThread;
private Thread mRecordAudioThread;
private Thread mSaveSoundFileThread;
private boolean mIsPlaying;
private SamplePlayer mPlayer;
private String mInfoContent;
private int mWidth;
private int mMaxPos;
private int mStartPos;
private int mEndPos;
private boolean mStartVisible;
private boolean mEndVisible;
private int mLastDisplayedStartPos;
private int mLastDisplayedEndPos;
private int mOffset;
private int mOffsetGoal;
private int mFlingVelocity;
private int mPlayStartMsec;
private int mPlayEndMsec;
private Handler mHandler;
Button pla;
MediaPlayer mediaPlayer;
boolean ismIsPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pla = (Button)findViewById(R.id.play);
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
mHandler = new Handler();
Uri uri = Uri.parse("/sdcard/audio_file.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
loadGui();
loadFromFile();
}
/**
* Called from both onCreate and onConfigurationChanged
* (if the user switched layouts)
*/
private void loadGui() {
// Inflate our UI from its XML layout description.
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
if (mSoundFile != null && !mWaveformView.hasSoundFile()) {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
}
}
private void loadFromFile() {
mFilename = "/sdcard/audio_file.mp3";
mFile = new File(mFilename);
SongMetadataReader metadataReader = new SongMetadataReader(
this, mFilename);
mTitle = metadataReader.mTitle;
mArtist = metadataReader.mArtist;
String titleLabel = mTitle;
if (mArtist != null && mArtist.length() > 0) {
titleLabel += " - " + mArtist;
}
setTitle(titleLabel);
mLoadingLastUpdateTime = getCurrentTime();
mLoadingKeepGoing = true;
mFinishActivity = false;
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setTitle("Loading...");
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mLoadingKeepGoing = false;
mFinishActivity = true;
}
});
mProgressDialog.show();
final SoundFile.ProgressListener listener =
new SoundFile.ProgressListener() {
public boolean reportProgress(double fractionComplete) {
long now = getCurrentTime();
if (now - mLoadingLastUpdateTime > 100) {
mProgressDialog.setProgress(
(int) (mProgressDialog.getMax() * fractionComplete));
mLoadingLastUpdateTime = now;
}
return mLoadingKeepGoing;
}
};
// Load the sound file in a background thread
mLoadSoundFileThread = new Thread() {
public void run() {
try {
mSoundFile = SoundFile.create(mFile.getAbsolutePath(), listener);
if (mSoundFile == null) {
mProgressDialog.dismiss();
String name = mFile.getName().toLowerCase();
String[] components = name.split("\\.");
String err;
if (components.length < 2) {
err = getResources().getString(
R.string.no_extension_error);
} else {
err = getResources().getString(
R.string.bad_extension_error) + " " +
components[components.length - 1];
}
final String finalErr = err;
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(new Exception(), finalErr);
}
};
mHandler.post(runnable);
return;
}
mPlayer = new SamplePlayer(mSoundFile);
} catch (final Exception e) {
mProgressDialog.dismiss();
e.printStackTrace();
mInfoContent = e.toString();
runOnUiThread(new Runnable() {
public void run() {
}
});
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(e, getResources().getText(R.string.read_error));
}
};
mHandler.post(runnable);
return;
}
mProgressDialog.dismiss();
if (mLoadingKeepGoing) {
Runnable runnable = new Runnable() {
public void run() {
finishOpeningSoundFile();
}
};
mHandler.post(runnable);
} else if (mFinishActivity){
MainActivity.this.finish();
}
}
};
mLoadSoundFileThread.start();
}
private void finishOpeningSoundFile() {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
Log.e("sound file",mFilename);
Log.e("sound", String.valueOf(mSoundFile));
}
/**
* Show a "final" alert dialog that will exit the activity
* after the user clicks on the OK button. If an exception
* is passed, it's assumed to be an error condition, and the
* dialog is presented as an error, and the stack trace is
* logged. If there's no exception, it's a success message.
*/
private void showFinalAlert(Exception e, CharSequence message) {
CharSequence title;
if (e != null) {
Log.e("Ringdroid", "Error: " + message);
Log.e("Ringdroid", getStackTrace(e));
title = getResources().getText(R.string.alert_title_failure);
setResult(RESULT_CANCELED, new Intent());
} else {
Log.v("Ringdroid", "Success: " + message);
title = getResources().getText(R.string.alert_title_success);
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void showFinalAlert(Exception e, int messageResourceId) {
showFinalAlert(e, getResources().getText(messageResourceId));
}
#Override
public void waveformTouchStart(float x) {
}
#Override
public void waveformTouchMove(float x) {
}
#Override
public void waveformTouchEnd() {
}
#Override
public void waveformFling(float x) {
}
#Override
public void waveformDraw() {
mWidth = mWaveformView.getMeasuredWidth();
if (mOffsetGoal != mOffset) {
// updateDisplay();
}
else if (mIsPlaying) {
// updateDisplay();
} else if (mFlingVelocity != 0) {
// updateDisplay();
}
}
private long getCurrentTime() {
return System.nanoTime() / 1000000;
}
private String getStackTrace(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
public void buttonClick(View view) {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
ismIsPlaying = true;
}
}
In your onDraw(Canvas canvas) add the following lines
if (i + start <= mPlaybackPos) {
Paint mPaint = new Paint(paint);
mPaint.setColor(Color.RED);
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
mPaint);
}
add them above the line:
if (i + start == mPlaybackPos) {
And if this works, consider to allocate the Paint-object outside the onDraw() method.

I lost my data when i scroll horizontal and vertical on view in Android

Em...the title is not clearly, here is my question: i custom a view to display calendar, my logic is when user swipe horizontal it can switch month of current year, when user swipe vertical it can switch year of current month, like image below:
Here is my all code below and i delete some useless code:
public class MonthView extends View {
private static final Region[][] MONTH_REGIONS = new Region[6][7];
private DPCManager mCManager = DPCManager.getInstance();
private DPTManager mTManager = DPTManager.getInstance();
private TextPaint mTextPaint;
private Paint mPaint;
private Scroller mScroller;
private DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
private AccelerateInterpolator accelerateInterpolator = new AccelerateInterpolator();
private OnDateChangeListener onDateChangeListener;
private ScaleAnimationListener scaleAnimationListener = new ScaleAnimationListener();
private DPMode mode;
private int indexYear, indexMonth;
private int centerYear, centerMonth;
private int leftYear, leftMonth;
private int rightYear, rightMonth;
private int topYear, topMonth;
private int bottomYear, bottomMonth;
private int width, height;
private int lastHeight, nextHeight;
private int baseSize;
private int sizeDecor, sizeDecor2x, sizeDecor3x;
private int lastPointX, lastPointY;
private int lastMoveX, lastMoveY;
private int criticalWidth, criticalHeight;
private float sizeTextGregorian, sizeTextFestival;
private float offsetYFestival1, offsetYFestival2;
private boolean isSlideV;
private Map<String, BGCircle> circlesAppear = new HashMap<>();
private Map<String, BGCircle> circlesDisappear = new HashMap<>();
private List<String> dateSelected = new ArrayList<>();
public interface OnDateChangeListener {
void onMonthChange(int month);
void onYearChange(int year);
}
public MonthView(Context context) {
this(context, null);
}
public MonthView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
mTextPaint = new TextPaint();
mTextPaint.setTextAlign(Paint.Align.CENTER);
mPaint = new Paint();
}
void setOnDateChangeListener(OnDateChangeListener onDateChangeListener) {
this.onDateChangeListener = onDateChangeListener;
}
void setMode(DPMode mode) {
this.mode = mode;
}
void setDate(int year, int month) {
centerYear = year;
centerMonth = month;
indexYear = 0;
indexMonth = 0;
computeDate();
requestLayout();
invalidate();
}
private void computeDate() {
rightYear = leftYear = centerYear;
topYear = centerYear - 1;
bottomYear = centerYear + 1;
topMonth = centerMonth;
bottomMonth = centerMonth;
rightMonth = centerMonth + 1;
leftMonth = centerMonth - 1;
if (centerMonth == 12) {
rightYear++;
rightMonth = 1;
}
if (centerMonth == 1) {
leftYear--;
leftMonth = 12;
}
if (null != onDateChangeListener) {
onDateChangeListener.onYearChange(centerYear);
onDateChangeListener.onMonthChange(centerMonth);
}
}
#Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
} else {
}
}
boolean isNewEvent = false;
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isNewEvent = true;
lastPointX = (int) event.getX();
lastPointY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
if (isNewEvent) {
if (Math.abs(lastPointX - event.getX()) > 100) {
isSlideV = false;
isNewEvent = false;
} else if (Math.abs(lastPointY - event.getY()) > 50) {
isSlideV = true;
isNewEvent = false;
}
}
if (isSlideV) {
int totalMoveY = (int) (lastPointY - event.getY()) + lastMoveY;
smoothScrollTo(0, totalMoveY);
} else {
int totalMoveX = (int) (lastPointX - event.getX()) + lastMoveX;
smoothScrollTo(totalMoveX, 0);
}
break;
case MotionEvent.ACTION_UP:
if (isSlideV) {
if (Math.abs(lastPointY - event.getY()) > 25) {
if (lastPointY < event.getY()) {
if (Math.abs(lastPointY - event.getY()) >= criticalHeight) {
indexYear--;
centerYear = centerYear - 1;
computeDate();
}
smoothScrollTo(0, height * indexYear);
lastMoveY = height * indexYear;
} else if (lastPointY > event.getY()) {
if (Math.abs(lastPointY - event.getY()) >= criticalHeight) {
indexYear++;
centerYear = centerYear + 1;
computeDate();
}
smoothScrollTo(0, height * indexYear);
lastMoveY = height * indexYear;
}
} else {
}
} else {
if (Math.abs(lastPointX - event.getX()) > 25) {
if (lastPointX > event.getX()) {
if (Math.abs(lastPointX - event.getX()) >= criticalWidth) {
indexMonth++;
centerMonth = (centerMonth + 1) % 13;
if (centerMonth == 0) {
centerMonth = 1;
centerYear++;
}
computeDate();
}
smoothScrollTo(width * indexMonth, 0);
lastMoveX = width * indexMonth;
} else if (lastPointX < event.getX()) {
if (Math.abs(lastPointX - event.getX()) >= criticalWidth) {
indexMonth--;
centerMonth = (centerMonth - 1) % 12;
if (centerMonth == 0) {
centerMonth = 12;
centerYear--;
}
computeDate();
}
smoothScrollTo(width * indexMonth, 0);
lastMoveX = width * indexMonth;
}
} else {
}
}
break;
}
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(measureWidth, measureWidth * 6 / 7F);
}
#Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
width = w;
height = h;
criticalWidth = (int) (1F / 5F * width);
criticalHeight = (int) (1F / 5F * height);
baseSize = w;
int sizeCell = (int) (baseSize / 7F);
sizeDecor = (int) (sizeCell / 3F);
sizeDecor2x = sizeDecor * 2;
sizeDecor3x = sizeDecor * 3;
sizeTextGregorian = baseSize / 20F;
mTextPaint.setTextSize(sizeTextGregorian);
float heightGregorian = mTextPaint.getFontMetrics().bottom - mTextPaint.getFontMetrics().top;
sizeTextFestival = baseSize / 40F;
mTextPaint.setTextSize(sizeTextFestival);
float heightFestival = mTextPaint.getFontMetrics().bottom - mTextPaint.getFontMetrics().top;
offsetYFestival1 = (((Math.abs(mTextPaint.ascent() + mTextPaint.descent())) / 2F) +
heightFestival / 2F + heightGregorian / 2F) / 2F;
offsetYFestival2 = offsetYFestival1 * 2F;
for (int i = 0; i < MONTH_REGIONS.length; i++) {
for (int j = 0; j < MONTH_REGIONS[i].length; j++) {
Region region = new Region();
region.set((j * sizeCell), (i * sizeCell), sizeCell + (j * sizeCell),
sizeCell + (i * sizeCell));
MONTH_REGIONS[i][j] = region;
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.LTGRAY);
draw(canvas, width * (indexMonth - 1), height * indexYear, leftYear, leftMonth);
draw(canvas, width * indexMonth, height * indexYear, centerYear, centerMonth);
draw(canvas, width * (indexMonth + 1), height * indexYear, rightYear, rightMonth);
draw(canvas, width * indexMonth, height * (indexYear - 1), topYear, topMonth);
draw(canvas, width * indexMonth, height * (indexYear + 1), bottomYear, bottomMonth);
}
private void draw(Canvas canvas, int x, int y, int year, int month) {
canvas.save();
canvas.translate(x, y);
DPInfo[][] info = mCManager.obtainDPInfo(year, month);
for (int i = 0; i < info.length; i++) {
for (int j = 0; j < info[i].length; j++) {
draw(canvas, MONTH_REGIONS[i][j].getBounds(), info[i][j]);
}
}
canvas.restore();
}
private void draw(Canvas canvas, Rect rect, DPInfo info) {
drawGregorian(canvas, rect, info.strG, info.isWeekend);
}
private void drawGregorian(Canvas canvas, Rect rect, String str, boolean isWeekend) {
mTextPaint.setTextSize(sizeTextGregorian);
if (isWeekend) {
mTextPaint.setColor(mTManager.colorWeekend());
} else {
mTextPaint.setColor(mTManager.colorG());
}
canvas.drawText(str, rect.centerX(), rect.centerY(), mTextPaint);
}
private void smoothScrollTo(int fx, int fy) {
int dx = fx - mScroller.getFinalX();
int dy = fy - mScroller.getFinalY();
smoothScrollBy(dx, dy);
}
private void smoothScrollBy(int dx, int dy) {
mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy, 500);
invalidate();
}
}
If i swipe vertical to switch year, for example 2015/7-->2016/7-->2017/7, it's run correctly, but now if i swipe horizontal to switch month, for example 2017/7-->2017/6, everything will not display:
That's mean only horizontal and vertical on current month can touch and display correctly, for example the default display month is 2015/7, when i swipe to 2016/7 or 2017/7, i can't get the correct display when i swipe to 2017/6 or 2017/8, only swipe back to 2015/7 to swipe correctly can get the correct display of 2015/6 and 2015/8.
This problem troubled me many days, the coordinates and data of months all correct, i don't know why it happen, hope and thanks for your answer.

View not displayed in my application

I Am developing android abacus application, in that i need to develope the user interface like the following and i am using the following logic. It compiles and executes without exceptions but the view is not visible.
So, please guide me how develope this.
**MainActivity**
public class Hello extends Activity implements SensorListener
{
private MyView myView;
private SensorManager sensorManager;
public void onAccuracyChanged(int paramInt1, int paramInt2)
{
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
Log.e("hello", "hello");
this.myView = new MyView(this);
setContentView(this.myView);
Log.e("hello", "hello after constructor");
this.sensorManager = ((SensorManager)getSystemService("sensor"));
this.myView.setTheme(2);
}
protected void onResume()
{
super.onResume();
this.sensorManager.registerListener(this, 3, 0);
}
public void onSensorChanged(int paramInt, float[] paramArrayOfFloat)
{
switch (paramInt)
{
default:
case 1:
case 2:
}
this.myView.resetTama();
do
{
do
return;
while (Math.abs(paramArrayOfFloat[2]) <= 50.0F);
}
while (Math.abs(paramArrayOfFloat[0]) <= 15.0F);
}
public void onWindowFocusChanged(boolean paramBoolean)
{
super.onWindowFocusChanged(paramBoolean);
if (paramBoolean)
this.myView.init();
}
}
**MyView class**
public class MyView extends RelativeLayout
{
private final int FP = -1;
private final int WC = -2;
public boolean disableApplication = false;
private int imgType = 1;
public boolean isBlack = false;
boolean isInitialized;
private Bitmap myBitmap;
private Paint myPaint = new Paint();
private int[] numbers;
private Tama[] oyatamaArray;
private Tama[][] tamaArray;
public MyView(Context paramContext)
{
super(paramContext);
Log.e("MyView", "MyView");
setFocusable(true);
setBackgroundResource(R.drawable.haikei);
this.myBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.tama);
this.numbers = new int[6];
//for displaying numbers
for (int i = 0; i<numbers.length; i++)
{
if (i >= this.numbers.length)
{
loadChangeThemeButton(paramContext);
new TextView(paramContext).setBackgroundResource(R.drawable.bar);
return;
}
this.numbers[i] = 0;
}
}
private void changeBackgroundImage()
{
int i = 1 + this.imgType;
this.imgType = i;
if (i > 3)
this.imgType = 1;
setTheme(this.imgType);
}
private void loadChangeThemeButton(Context paramContext)
{
ImageButton localImageButton = new ImageButton(paramContext);
localImageButton.setBackgroundResource(R.drawable.themebutton);
RelativeLayout.LayoutParams localLayoutParams = new RelativeLayout.LayoutParams(-2, -2);
localLayoutParams.addRule(9);
localLayoutParams.addRule(12);
localLayoutParams.setMargins(0, 0, 30, 30);
addView(localImageButton, localLayoutParams);
localImageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramView)
{
MyView.this.changeBackgroundImage();
}
});
}
private Bitmap returnNumberImg(Resources paramResources, int paramInt)
{
switch (paramInt)
{
default:
return BitmapFactory.decodeResource(paramResources, R.drawable.n0);
case 1:
return BitmapFactory.decodeResource(paramResources, R.drawable.n1);
case 2:
return BitmapFactory.decodeResource(paramResources, R.drawable.n2);
case 3:
return BitmapFactory.decodeResource(paramResources, R.drawable.n3);
case 4:
return BitmapFactory.decodeResource(paramResources, R.drawable.n4);
case 5:
return BitmapFactory.decodeResource(paramResources, R.drawable.n5);
case 6:
return BitmapFactory.decodeResource(paramResources, R.drawable.n6);
case 7:
return BitmapFactory.decodeResource(paramResources, R.drawable.n7);
case 8:
return BitmapFactory.decodeResource(paramResources, R.drawable.n8);
case 9:
}
return BitmapFactory.decodeResource(paramResources, R.drawable.n9);
}
private void settingTamasTouchX(int paramInt1, int paramInt2)
{
int i = 0;
if (i >= this.oyatamaArray.length);
int k;
for (int j = 0; ; j++)
{
if (j >= this.tamaArray.length)
{
return;
}
k = 0;
if (k < this.tamaArray[j].length)
{
if (this.tamaArray[j][k].checkArea(paramInt1, paramInt2));
for (this.tamaArray[j][k].touchX = paramInt1; ; this.tamaArray[j][k].touchX = 0)
{
k++;
break;
}
// break label90;
}
}
}
public void init()
{
int i = getHeight() / 7;
int[] arrayOfInt = new int[6];
int j = 5;
//if (j < 0){
this.oyatamaArray = new Tama[6];
//}
int m;
int i1 = 0;
for (int k = 0; ; k++)
{
if (k >= this.oyatamaArray.length)
{
this.tamaArray = ((Tama[][])Array.newInstance(Tama.class, new int[] { 6, 4 }));
m = 0;
if (m < this.tamaArray.length)
{
for (int n = 0; ; n++)
{
if (n >= this.tamaArray[m].length)
{
m++;
break;
}
this.tamaArray[m][n] = new Tama(40 + n * 37, arrayOfInt[m] - 32, n + m * 10);
}
// break label154;
}
i1 = 0;
if (i1 < this.tamaArray.length)
{
for (int i2 = 0; ; i2++)
{
if (i2 >= this.tamaArray[i1].length)
{
i1++;
break;
}
if (i2 != this.tamaArray[i1].length - 1)
this.tamaArray[i1][i2].ueTama = this.tamaArray[i1][(i2 + 1)];
if (i2 == 0)
continue;
this.tamaArray[i1][i2].shitaTama = this.tamaArray[i1][(i2 - 1)];
}
// break label222;
}
this.isInitialized = true;
return;
}
this.oyatamaArray[k] = new Tama(279, arrayOfInt[k] - 32, k);
this.oyatamaArray[k].isOya = true;
}
}
#Override
protected void onDraw(Canvas paramCanvas)
{
Log.e("this is",".........onDraw");
if (!this.isInitialized)
init();
int i = 0;
Resources localResources;
int m;
while (true)
{
int j;
if (i >= this.oyatamaArray.length)
{
j = 0;
if (j >= this.tamaArray.length)
{
localResources = getContext().getResources();
m = 0;
if (m < 7)
break;
return;
}
}
else
{
paramCanvas.drawBitmap(this.myBitmap, this.oyatamaArray[i].getX(), this.oyatamaArray[i].getY(), this.myPaint);
i++;
continue;
}
for (int k = 0; ; k++)
{
if (k >= this.tamaArray[j].length)
{
j++;
break;
}
paramCanvas.drawBitmap(this.myBitmap, this.tamaArray[j][k].getX(), this.tamaArray[j][k].getY(), this.myPaint);
}
}
if (this.numbers.length <= m)
{
for (Bitmap localBitmap = BitmapFactory.decodeResource(localResources, R.drawable.space); ; localBitmap = returnNumberImg(localResources, this.numbers[m]))
{
paramCanvas.drawBitmap(localBitmap, 8.0F, getHeight() / 2 + m * 18, this.myPaint);
m++;
break;
}
}
}
public boolean onTouchEvent(MotionEvent paramMotionEvent)
{
int i = (int)paramMotionEvent.getX();
int j = (int)paramMotionEvent.getY();
if ((paramMotionEvent.getAction() == 0) && (i >= 0) && (i <= 40) && (410 <= j) && (j <= 430))
changeBackgroundImage();
if (paramMotionEvent.getAction() == 0)
settingTamasTouchX(i, j);
if (1 == paramMotionEvent.getAction())
settingTamasTouchX(0, 0);
int k;
int m = 0;
if (2 == paramMotionEvent.getAction())
{
k = 0;
if (k >= this.oyatamaArray.length)
{
m = 0;
if (m < this.tamaArray.length)
{
for (int n = 0; ; n++)
{
if (n >= this.tamaArray[m].length)
{
m++;
break;
}
this.tamaArray[m][n].checkAndSetArea(i, j);
if (!this.tamaArray[m][n].isUp)
continue;
int[] arrayOfInt = this.numbers;
arrayOfInt[m] = (1 + arrayOfInt[m]);
}
// break label164;
}
invalidate();
}
}
else
{
return true;
}
this.oyatamaArray[k].checkAndSetArea(i, j);
if (this.oyatamaArray[k].isUp)
this.numbers[k] = 5;
while (true)
{
k++;
break;
}
// label164:
return disableApplication;
}
public void resetTama()
{
int j;
for (int i = 0; ; i++)
{
if (i >= this.oyatamaArray.length)
{
j = 0;
if (j < this.tamaArray.length)
break;
invalidate();
return;
}
this.oyatamaArray[i].moveX(this.oyatamaArray[i].startX);
this.oyatamaArray[i].isUp = false;
this.numbers[i] = 0;
}
for (int k = 0; ; k++)
{
if (k >= this.tamaArray[j].length)
{
j++;
break;
}
this.tamaArray[j][k].moveX(this.tamaArray[j][k].startX);
this.tamaArray[j][k].isUp = false;
}
}
public void sensorChange(float[] paramArrayOfFloat)
{
int i = 0;
if (paramArrayOfFloat[2] < -50.0F)
i = 0 - 3;
int k;
while (true)
{
int j = 0;
if (j >= this.oyatamaArray.length)
{
k = 0;
if (k < this.tamaArray.length)
break;
if (i != 0)
invalidate();
return;
}
else
{
this.oyatamaArray[j].moveX(i + this.oyatamaArray[j].getX());
if (this.oyatamaArray[j].isUp)
this.numbers[j] = 5;
while (true)
{
j++;
break;
}
}
}
for (int m = 0; ; m++)
{
if (m >= this.tamaArray[k].length)
{
k++;
break;
}
this.tamaArray[k][m].moveX(i + this.tamaArray[k][m].getX());
if (!this.tamaArray[k][m].isUp)
continue;
int[] arrayOfInt = this.numbers;
arrayOfInt[k] = (1 + arrayOfInt[k]);
}
}
public void setTheme(int paramInt)
{
Resources localResources = getContext().getResources();
if (paramInt == 1)
{
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama);
setBackgroundResource(R.drawable.haikei);
}
while (true)
{
invalidate();
// return;
if (paramInt == 2)
{
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama2);
setBackgroundResource(R.drawable.haikei1);
continue;
}
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama3);
setBackgroundResource(R.drawable.haikei1);
}
}
}
Try this (instead of the setContentView )
this.myView = new MyView(this);
this.myView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
this.addContentView(myView, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

TiledLayer equivalent in Android [duplicate]

This question already has answers here:
Android Tile Bitmap
(8 answers)
Closed 8 years ago.
To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?
You can use this class as a equivalent "TiledLayer class of jme":
package net.obviam.walking;
import java.util.ArrayList;
import com.kilobolt.framework.Graphics;
import com.kilobolt.framework.Image;
import com.kilobolt.framework.implementation.AndroidImage;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Rect;
public class TiledLayer {
public static final int DIR_LEFT = 0;
public static final int DIR_RIGHT = 1;
public static final int DIR_UP = 2;
public static final int DIR_DOWN = 3;
private int cellWidth;
private int cellHeight;
private int yPosition = 0, xPosition = 0;
private int[][] grid;
private Image image;
private Bitmap tileArray[];
private int[] tileXPositions;
private int[] tileYPositions;
private ArrayList animatedTiles;
private int numberOfTiles;
private int numberOfColumns;
private int numberOfRows;
private int gridColumns;
private int gridRows, width, height;
int tileCounter;
public TiledLayer(Image image, int columns, int rows, int tileWidth,
int tileHeight, int width, int height) {
this.grid = new int[columns][rows];
this.gridColumns = columns;
this.gridRows = rows;
this.width = columns * tileWidth;
this.height = rows * tileHeight;
this.animatedTiles = new ArrayList();
this.cellWidth = tileWidth;
this.cellHeight = tileHeight;
int r = image.getHeight() / tileHeight;
int c = image.getWidth() / tileWidth;
tileArray = new Bitmap[(r * c) + 1];
setStaticTileSet(image, tileWidth, tileHeight);
}
public TiledLayer(Bitmap image, int columns, int rows, int tileWidth,
int tileHeight, int width, int height) {
this.grid = new int[columns][rows];
this.gridColumns = columns;
this.gridRows = rows;
this.width = columns * tileWidth;
this.height = rows * tileHeight;
this.animatedTiles = new ArrayList();
this.cellWidth = tileWidth;
this.cellHeight = tileHeight;
int r = image.getHeight() / tileHeight;
int c = image.getWidth() / tileWidth;
tileArray = new Bitmap[(r * c) + 1];
setStaticTileSet(image, tileWidth, tileHeight);
}
public void setStaticTileSet(Image image, int tileWidth, int tileHeight) {
tileArray[0] = Bitmap.createBitmap(tileWidth, tileHeight,
Config.ARGB_4444);
int rows = image.getHeight() / tileHeight;
int columns = image.getWidth() / tileWidth;
numberOfTiles = rows * columns;
for (int i = 0; i < rows; i++) {
yPosition = i * tileHeight;
for (int j = 0; j < columns; j++) {
xPosition = j * tileWidth;
tileCounter++;
tileArray[tileCounter] = Bitmap.createBitmap(
((AndroidImage) image).bitmap, xPosition, yPosition,
tileWidth, tileHeight);
}
}
if (gridColumns * gridRows < this.numberOfTiles) {
// clear the grid, when there are not as many tiles as in the
// previous set:
for (int i = 0; i < this.grid.length; i++) {
for (int j = 0; j < this.grid[i].length; j++) {
this.grid[i][j] = 0;
}
}
}
}
public void setStaticTileSet(Bitmap image, int tileWidth, int tileHeight) {
tileArray[0] = Bitmap.createBitmap(tileWidth, tileHeight,
Config.ARGB_4444);
int rows = image.getHeight() / tileHeight;
int columns = image.getWidth() / tileWidth;
numberOfTiles = rows * columns;
for (int i = 0; i < rows; i++) {
yPosition = i * tileHeight;
for (int j = 0; j < columns; j++) {
xPosition = j * tileWidth;
tileCounter++;
tileArray[tileCounter] = Bitmap.createBitmap(image, xPosition,
yPosition, tileWidth, tileHeight);
}
}
if (gridColumns * gridRows < this.numberOfTiles) {
// clear the grid, when there are not as many tiles as in the
// previous set:
for (int i = 0; i < this.grid.length; i++) {
for (int j = 0; j < this.grid[i].length; j++) {
this.grid[i][j] = 0;
}
}
}
}
public int createAnimatedTile(int staticTileIndex) {
if (staticTileIndex >= this.numberOfTiles) {
throw new IllegalArgumentException("invalid static tile index: "
+ staticTileIndex + " (there are only ["
+ this.numberOfTiles + "] tiles available.");
}
this.animatedTiles.add(new Integer(staticTileIndex));
return -1 * (this.animatedTiles.size() - 1);
}
public void setAnimatedTile(int animatedTileIndex, int staticTileIndex) {
if (staticTileIndex >= this.numberOfTiles) {
}
int animatedIndex = (-1 * animatedTileIndex) - 1;
this.animatedTiles.set(animatedIndex, new Integer(staticTileIndex));
}
public int getAnimatedTile(int animatedTileIndex) {
int animatedIndex = (-1 * animatedTileIndex) - 1;
Integer animatedTile = (Integer) this.animatedTiles.get(animatedIndex);
return animatedTile.intValue();
}
public void setCell(int col, int row, int tileIndex) {
if (tileIndex >= this.numberOfTiles) {
throw new IllegalArgumentException("invalid static tile index: "
+ tileIndex + " (there are only [" + this.numberOfTiles
+ "] tiles available.");
}
this.grid[col][row] = tileIndex;
}
public int getCell(int col, int row) {
return this.grid[col][row];
}
public boolean checkTileCollision(Sprite sp, int dir, int speed) {
int curRow, curCollumn;
int leftTile = 0, rightTile = 0, upTile = 0, downTile = 0;
curRow = sp.getY() / cellHeight;
curCollumn = sp.getX() / cellWidth;
leftTile = grid[curCollumn - 1][curRow];
rightTile = grid[curCollumn + 1][curRow];
upTile = grid[curCollumn][curRow - 1];
downTile = grid[curCollumn][curRow + 1];
if (dir == DIR_RIGHT
&& (sp.getX() + sp.getWidth() + speed) <= (curCollumn + 1)
* cellWidth)
return false;
else if (dir == DIR_RIGHT
&& ((sp.getX() + sp.getWidth() + speed)) > (curCollumn + 1)
* cellWidth && rightTile != 1)
return true;
else if (dir == DIR_LEFT
&& (sp.getX() - speed) >= (curCollumn) * cellWidth)
return false;
else if (dir == DIR_LEFT
&& (sp.getX() - speed) < (curCollumn) * cellWidth
&& leftTile != 1)
return true;
else if (dir == DIR_UP && (sp.getY() - speed) >= (curRow) * cellHeight)
return false;
else if (dir == DIR_UP && (sp.getY() - speed) < (curRow) * cellHeight
&& upTile != 1)
return true;
else if (dir == DIR_DOWN
&& (sp.getY() + sp.getHeight() + speed) <= (curRow + 1)
* cellHeight)
return false;
else if (dir == DIR_DOWN
&& (sp.getY() + sp.getHeight() + speed) > (curRow + 1)
* cellHeight && downTile != 1)
return true;
else
return false;
}
public void fillCells(int col, int row, int numCols, int numRows,
int tileIndex) {
if (tileIndex >= this.numberOfTiles) {
throw new IllegalArgumentException("invalid static tile index: "
+ tileIndex + " (there are only [" + this.numberOfTiles
+ "] tiles available.");
}
int endCols = col + numCols;
int endRows = row + numRows;
for (int i = col; i < endCols; i++) {
for (int j = row; j < endRows; j++) {
this.grid[i][j] = tileIndex;
}
}
}
public final int getCellWidth() {
return this.cellWidth;
}
public final int getCellHeight() {
return this.cellHeight;
}
public final int getColumns() {
return this.gridColumns;
}
public final int getRows() {
return this.gridRows;
}
public final void paint(Graphics g) {
for (int i = 0; i < this.gridRows; i++) {
for (int j = 0; j < this.gridColumns; j++) {
Bitmap bmp = tileArray[grid[j][i]];
g.drawImage(bmp, j * cellWidth, i * cellHeight);
}
}
}
public final void paint(Canvas c) {
for (int i = 0; i < this.gridRows; i++) {
for (int j = 0; j < this.gridColumns; j++) {
Bitmap bmp = tileArray[grid[j][i]];
c.drawBitmap(bmp, j * cellWidth, i * cellHeight, null);
// g.drawImage(bmp, j*cellWidth,i*cellHeight);
}
}
}
}

Categories

Resources