View not displayed in my application - android

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));

Related

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

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.
}
}

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.

onDraw method not called in my application

i am developing an application, in that onDraw() is called. i am using the following logic.
so, please guide where i did the mistake.
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);
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
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import java.lang.reflect.Array;
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);
setWillNotDraw(false);
this.myBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.tama);
this.numbers = new int[6];
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 dispatchDraw(Canvas canvas){
super.dispatchDraw(canvas);
Log.e("......this.........","drawing");
}
#Override
protected void onDraw(Canvas paramCanvas)
{
super.onDraw(paramCanvas);
Log.e("This on draw","....yes");
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, 2130837523); ; 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(2130837510);
continue;
}
this.myBitmap = BitmapFactory.decodeResource(localResources, R.drawable.tama3);
setBackgroundResource(2130837510);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="#id/FrameLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Try the below it works
To the question posted before edit.
If you're extending a ViewGroup you should override dispatchDraw() instead of onDraw().
Discussion on the topic #
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/oLccWfszuUo
public class Hello extends Activity {
private MyView myView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
Log.e("hello", "hello");
this.myView = new MyView(this);
setContentView(this.myView);
}
public class MyView extends RelativeLayout
{
private Paint myPaint = new Paint();
private int[] numbers;
public MyView(Context paramContext)
{
super(paramContext);
Log.e("MyView", "MyView");
setFocusable(true);
setBackgroundResource(R.drawable.ic_launcher);
}
#Override
protected void dispatchDraw(Canvas canvas){
super.dispatchDraw(canvas);
Log.i("...............","drawing");
}
}
}
protected void dispatchDraw (Canvas canvas)
Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).
Parameters
canvas the canvas on which to draw the view
If you Override onDraw inthe constructor call setWillNotDraw(false) then it should work.
http://developer.android.com/reference/android/view/View.html#setWillNotDraw(boolean)
public MyView(Context paramContext)
{
super(paramContext);
Log.e("MyView", "MyView");
setFocusable(true);
setBackgroundResource(R.drawable.ic_launcher);
setWillNotDraw(false);
}

why jd-gui lost some info when decompile a .class file?

I have decompiled a class by jd-gui below, but I am unable to understand how the "linearLayout" is being initialized and why linearLayout.startAnimation(animationset) should be invoked, the LockScreen member "linearLayout" is not referred to any instance.
Can anybody tell me how this work? Is it possible for jd-gui lose something while decompilin a .class file ?
the decompiled file below:
// Referenced classes of package com.android.internal.policy.impl:
// KeyguardScreen, KeyguardStatusViewManager, DrawWaterWave, KeyguardUpdateMonitor,
// KeyguardScreenCallback
class LockScreen extends RelativeLayout
implements KeyguardScreen
{
class MultiWaveViewMethods
implements com.android.internal.widget.multiwaveview.MultiWaveView.OnTriggerListener, UnlockWidgetCommonMethods
{
private boolean mCameraDisabled;
private final MultiWaveView mMultiWaveView;
final LockScreen this$0;
public View getView()
{
return mMultiWaveView;
}
public void onGrabbed(View view, int i)
{
}
public void onGrabbedStateChange(View view, int i)
{
if (i != 0)
mCallback.pokeWakelock();
}
public void onReleased(View view, int i)
{
}
public void onTrigger(View view, int i)
{
if (i != 0 && i != 1) goto _L2; else goto _L1
_L1:
mCallback.goToUnlockScreen();
_L4:
return;
_L2:
if (i == 2 || i == 3)
if (!mCameraDisabled)
{
Intent intent = new Intent("android.intent.action.CAMERA_BUTTON", null);
mContext.sendOrderedBroadcast(intent, null);
mCallback.goToUnlockScreen();
} else
{
toggleRingMode();
mUnlockWidgetMethods.updateResources();
mCallback.pokeWakelock();
}
if (true) goto _L4; else goto _L3
_L3:
}
public void ping()
{
mMultiWaveView.ping();
}
public void reset(boolean flag)
{
mMultiWaveView.reset(flag);
}
public void updateResources()
{
int i;
if (mCameraDisabled)
{
if (mSilentMode)
i = 0x107000b;
else
i = 0x107000e;
} else
{
i = 0x1070010;
}
mMultiWaveView.setTargetResources(i);
}
MultiWaveViewMethods(MultiWaveView multiwaveview)
{
boolean flag = true;
this$0 = LockScreen.this;
super();
mMultiWaveView = multiwaveview;
if (mLockPatternUtils.getDevicePolicyManager().getCameraDisabled(null))
{
Log.v("LockScreen", "Camera disabled by Device Policy");
mCameraDisabled = flag;
} else
{
if (mMultiWaveView.getTargetResourceId() == 0x1070010)
flag = false;
mCameraDisabled = flag;
}
}
}
class SlidingTabMethods
implements com.android.internal.widget.SlidingTab.OnTriggerListener, UnlockWidgetCommonMethods
{
private final SlidingTab mSlidingTab;
final LockScreen this$0;
public View getView()
{
return mSlidingTab;
}
public void onGrabbedStateChange(View view, int i)
{
if (i == 2)
{
mSilentMode = isSilentMode();
SlidingTab slidingtab = mSlidingTab;
int j;
if (mSilentMode)
j = 0x104030b;
else
j = 0x104030c;
slidingtab.setRightHintText(j);
}
if (i != 0)
mCallback.pokeWakelock();
}
public void onTrigger(View view, int i)
{
if (i != 1) goto _L2; else goto _L1
_L1:
mCallback.goToUnlockScreen();
_L4:
return;
_L2:
if (i == 2)
{
toggleRingMode();
mCallback.pokeWakelock();
}
if (true) goto _L4; else goto _L3
_L3:
}
public void ping()
{
}
public void reset(boolean flag)
{
mSlidingTab.reset(flag);
}
public void updateResources()
{
int i = 1;
SlidingTab slidingtab;
int j;
int k;
int l;
int i1;
if (!mSilentMode || mAudioManager.getRingerMode() != i)
i = 0;
slidingtab = mSlidingTab;
if (mSilentMode)
{
if (i != 0)
j = 0x10802cc;
else
j = 0x10802c9;
} else
{
j = 0x10802ca;
}
if (mSilentMode)
k = 0x1080398;
else
k = 0x1080395;
if (mSilentMode)
l = 0x1080381;
else
l = 0x1080380;
if (mSilentMode)
i1 = 0x1080394;
else
i1 = 0x1080393;
slidingtab.setRightTabResources(j, k, l, i1);
}
SlidingTabMethods(SlidingTab slidingtab)
{
this$0 = LockScreen.this;
super();
mSlidingTab = slidingtab;
}
}
private static interface UnlockWidgetCommonMethods
{
public abstract View getView();
public abstract void ping();
public abstract void reset(boolean flag);
public abstract void updateResources();
}
class WaveViewMethods
implements com.android.internal.widget.WaveView.OnTriggerListener, UnlockWidgetCommonMethods
{
private final WaveView mWaveView;
final LockScreen this$0;
public View getView()
{
return mWaveView;
}
public void onGrabbedStateChange(View view, int i)
{
if (i == 10)
mCallback.pokeWakelock(30000);
}
public void onTrigger(View view, int i)
{
Log.i("LockScreen", (new StringBuilder()).append("onTrigger, whichHandle=").append(i).toString());
if (i == 10)
{
Log.i("LockScreen", "onTrigger, requestUnlockScreen");
requestUnlockScreen();
}
}
public void ping()
{
}
public void reset(boolean flag)
{
mWaveView.reset();
}
public void updateResources()
{
}
WaveViewMethods(WaveView waveview)
{
this$0 = LockScreen.this;
super();
mWaveView = waveview;
}
}
private static final boolean DBG = true;
private static final String ENABLE_MENU_KEY_FILE = "/data/local/enable_menu_key";
static final String LOCKSCREEN_WALLPAPER = "lockScreenWallpaper";
static final File LOCKSCREEN_WALLPAPER_DIR;
static final File LOCKSCREEN_WALLPAPER_FILE;
private static final int MASTER_STREAM_TYPE = 3;
private static final int ON_RESUME_PING_DELAY = 500;
private static final int STAY_ON_WHILE_GRABBED_TIMEOUT = 30000;
private static final String TAG = "LockScreen";
private static final int WAIT_FOR_ANIMATION_TIMEOUT;
Bitmap BitmapLock;
Bitmap BitmapLockin;
Bitmap BitmapLockout;
final float MAX_LOCK_VOLUME = 0.2F;
final float MIN_LOCK_VOLUME = 0.05F;
int circleinwidth;
int circlewidth;
private ImageView imageCircle;
private LinearLayout linearLayout;
private LinearLayout linearLayout2;
private int locationBrower[];
private int locationCall[];
private int locationCamera[];
private boolean mAnimate;
private AudioManager mAudioManager;
private ImageView mBrower;
private boolean mBrowerPress;
private ImageView mCall;
private boolean mCallPress;
private KeyguardScreenCallback mCallback;
private ImageView mCamera;
private boolean mCameraPress;
private RelativeLayout mChildView;
private Context mContext;
private int mCreationOrientation;
private boolean mDMLock;
private boolean mEnableMenuKeyInLockScreen;
private float mFirstMotionX;
private float mFirstMotionY;
private HDMINative mHDMI;
private int mKeyboardHidden;
private float mLastMotionX;
private float mLastMotionY;
private LockPatternUtils mLockPatternUtils;
private int mLockSoundId;
private int mLockSoundStreamId;
private SoundPool mLockSounds;
private TextView mLockString;
private int mMasterStreamMaxVolume;
private float mMotionDeltaX;
private float mMotionDeltaY;
private int mMoveFirst;
private boolean mMoveFirst2;
private final Runnable mOnResumePing = new Runnable() {
final LockScreen this$0;
public void run()
{
if (mDMLock)
mUnlockWidgetMethods.ping();
}
{
this$0 = LockScreen.this;
super();
}
};
Paint mPaintin;
Paint mPaintout;
private boolean mScreenOn;
private boolean mSilentMode;
private KeyguardStatusViewManager mStatusViewManager;
private boolean mTouching;
private boolean mUnlock;
private int mUnlockSoundId;
private View mUnlockWidget;
private UnlockWidgetCommonMethods mUnlockWidgetMethods;
private KeyguardUpdateMonitor mUpdateMonitor;
private final WallpaperManager mWallpaperManager;
private float mYVelocity;
DrawWaterWave m_DrawWaterWave;
LockScreen(Context context, Configuration configuration, LockPatternUtils lockpatternutils, KeyguardUpdateMonitor keyguardupdatemonitor, KeyguardScreenCallback keyguardscreencallback)
{
super(context);
mHDMI = new HDMINative();
BitmapLockin = null;
BitmapLockout = null;
BitmapLock = null;
circleinwidth = 75;
circlewidth = 180;
mMoveFirst = 0;
mMoveFirst2 = false;
mPaintin = null;
mPaintout = null;
mTouching = false;
mAnimate = false;
mUnlock = false;
mScreenOn = false;
mDMLock = false;
mContext = null;
mCallPress = false;
mBrowerPress = false;
mCameraPress = false;
locationCall = new int[2];
locationBrower = new int[2];
locationCamera = new int[2];
mContext = context;
mLockPatternUtils = lockpatternutils;
mUpdateMonitor = keyguardupdatemonitor;
mCallback = keyguardscreencallback;
mEnableMenuKeyInLockScreen = shouldEnableMenuKey();
mWallpaperManager = WallpaperManager.getInstance(context);
mCreationOrientation = configuration.orientation;
mKeyboardHidden = configuration.hardKeyboardHidden;
LayoutInflater layoutinflater = LayoutInflater.from(context);
Log.v("LockScreen", (new StringBuilder()).append("Creation orientation = ").append(mCreationOrientation).toString());
Log.i("LockScreen", "we will initialize the LockScreen single portrait layout");
layoutinflater.inflate(0x109005a, this, true);
mChildView = (RelativeLayout)findViewById(0x10202b4);
setBackDrawable();
mStatusViewManager = new KeyguardStatusViewManager(this, mUpdateMonitor, mLockPatternUtils, mCallback, false);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(0x60000);
mAudioManager = (AudioManager)mContext.getSystemService("audio");
mSilentMode = isSilentMode();
m_DrawWaterWave = new DrawWaterWave(context);
if (mDMLock)
{
mUnlockWidget = findViewById(0x102029b);
android.content.ContentResolver contentresolver;
String s;
StringBuilder stringbuilder;
if (mUnlockWidget instanceof SlidingTab)
{
SlidingTab slidingtab = (SlidingTab)mUnlockWidget;
slidingtab.setHoldAfterTrigger(true, false);
slidingtab.setLeftHintText(0x104030a);
slidingtab.setLeftTabResources(0x10802cb, 0x1080396, 0x1080377, 0x108038a);
SlidingTabMethods slidingtabmethods = new SlidingTabMethods(slidingtab);
slidingtab.setOnTriggerListener(slidingtabmethods);
mUnlockWidgetMethods = slidingtabmethods;
} else
if (mUnlockWidget instanceof WaveView)
{
WaveView waveview = (WaveView)mUnlockWidget;
WaveViewMethods waveviewmethods = new WaveViewMethods(waveview);
waveview.setOnTriggerListener(waveviewmethods);
mUnlockWidgetMethods = waveviewmethods;
} else
if (mUnlockWidget instanceof MultiWaveView)
{
MultiWaveView multiwaveview = (MultiWaveView)mUnlockWidget;
MultiWaveViewMethods multiwaveviewmethods = new MultiWaveViewMethods(multiwaveview);
multiwaveview.setOnTriggerListener(multiwaveviewmethods);
mUnlockWidgetMethods = multiwaveviewmethods;
} else
{
throw new IllegalStateException((new StringBuilder()).append("Unrecognized unlock widget: ").append(mUnlockWidget).toString());
}
mUnlockWidgetMethods.updateResources();
}
BitmapLockin = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080617)).getBitmap();
BitmapLockout = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080619)).getBitmap();
BitmapLock = ((BitmapDrawable)(BitmapDrawable)getResources().getDrawable(0x1080618)).getBitmap();
imageCircle = (ImageView)findViewById(0x10202c7);
mCall = (ImageView)findViewById(0x10202c0);
mBrower = (ImageView)findViewById(0x10202c1);
mCamera = (ImageView)findViewById(0x10202c2);
mLockString = (TextView)findViewById(0x10202bd);
mPaintin = new Paint();
mPaintout = new Paint();
contentresolver = mContext.getContentResolver();
mLockSounds = new SoundPool(1, 1, 0);
s = android.provider.Settings.System.getString(contentresolver, "lock_sound");
if (s != null)
mLockSoundId = mLockSounds.load(s, 1);
if (s == null || mLockSoundId == 0)
Log.d("LockScreen", (new StringBuilder()).append("failed to load sound from ").append(s).toString());
if ("/system/media/audio/ui/Effect_Tick.ogg" != null)
mUnlockSoundId = mLockSounds.load("/system/media/audio/ui/Effect_Tick.ogg", 1);
if ("/system/media/audio/ui/Effect_Tick.ogg" == null || mUnlockSoundId == 0)
Log.d("LockScreen", (new StringBuilder()).append("failed to load sound from ").append("/system/media/audio/ui/Effect_Tick.ogg").toString());
if (mUpdateMonitor.DM_IsLocked() && mDMLock)
{
Log.i("LockScreen", "we should hide unlock widget");
mUnlockWidget.setVisibility(4);
}
if (mDMLock)
{
stringbuilder = (new StringBuilder()).append("*** LockScreen accel is ");
String s1;
if (mUnlockWidget.isHardwareAccelerated())
s1 = "on";
else
s1 = "off";
Log.v("LockScreen", stringbuilder.append(s1).toString());
}
}
private boolean isScreenOn()
{
PowerManager powermanager = (PowerManager)mContext.getSystemService("power");
boolean flag = false;
if (powermanager != null)
{
flag = powermanager.isScreenOn();
Log.d("LockScreen", (new StringBuilder()).append("screenOn:").append(flag).toString());
}
return flag;
}
private boolean isSilentMode()
{
boolean flag;
if (mAudioManager.getRingerMode() != 2)
flag = true;
else
flag = false;
return flag;
}
private void playSounds(boolean flag)
{
if (android.provider.Settings.System.getInt(mContext.getContentResolver(), "lockscreen_sounds_enabled", 1) != 1) goto _L2; else goto _L1
_L1:
int i;
if (flag)
i = mLockSoundId;
else
i = mUnlockSoundId;
mLockSounds.stop(mLockSoundStreamId);
if (mAudioManager != null) goto _L4; else goto _L3
_L3:
mAudioManager = (AudioManager)mContext.getSystemService("audio");
if (mAudioManager != null) goto _L5; else goto _L2
_L2:
return;
_L5:
mMasterStreamMaxVolume = mAudioManager.getStreamMaxVolume(3);
_L4:
int j = mAudioManager.getStreamVolume(3);
if (j != 0)
{
float f = 0.05F + 0.15F * ((float)j / (float)mMasterStreamMaxVolume);
Log.d("LockScreen", (new StringBuilder()).append("playSounds").append(i).toString());
mLockSoundStreamId = mLockSounds.play(i, f, f, 1, 0, 1.0F);
}
if (true) goto _L2; else goto _L6
_L6:
}
private void requestUnlockScreen()
{
postDelayed(new Runnable() {
final LockScreen this$0;
public void run()
{
mCallback.goToUnlockScreen();
}
{
this$0 = LockScreen.this;
super();
}
}, 0L);
}
private void setBackDrawable()
{
}
private boolean shouldEnableMenuKey()
{
boolean flag = getResources().getBoolean(0x111001a);
boolean flag1 = ActivityManager.isRunningInTestHarness();
boolean flag2 = (new File("/data/local/enable_menu_key")).exists();
boolean flag3;
if (!flag || flag1 || flag2)
flag3 = true;
else
flag3 = false;
return flag3;
}
private void toggleRingMode()
{
int i = 1;
boolean flag;
if (!mSilentMode)
flag = i;
else
flag = false;
mSilentMode = flag;
if (mSilentMode)
{
int j;
AudioManager audiomanager;
if (android.provider.Settings.System.getInt(mContext.getContentResolver(), "vibrate_in_silent", i) == i)
j = i;
else
j = 0;
audiomanager = mAudioManager;
if (j == 0)
i = 0;
audiomanager.setRingerMode(i);
} else
{
mAudioManager.setRingerMode(2);
}
}
public void cleanUp()
{
mUpdateMonitor.removeCallback(this);
mLockPatternUtils = null;
mUpdateMonitor = null;
mCallback = null;
}
protected void dispatchDraw(Canvas canvas)
{
if ((mTouching || mMoveFirst != 0) && !mDMLock)
{
super.dispatchDraw(canvas);
canvas.save();
canvas.translate(0.0F, 0.0F);
if (mMotionDeltaX * mMotionDeltaX + mMotionDeltaY * mMotionDeltaY > (float)(circleinwidth * circleinwidth))
{
float f = mMotionDeltaX * mMotionDeltaX + mMotionDeltaY * mMotionDeltaY;
float f1 = (0 + (0 + circlewidth)) * (0 + (0 + circlewidth));
float f2 = (255F * f) / f1;
if (f2 >= 255F)
f2 = 255F;
mPaintin.setAlpha((int)(255F - f2));
} else
{
mPaintin.setAlpha(255);
}
canvas.drawBitmap(BitmapLockin, mFirstMotionX - (float)circlewidth, mFirstMotionY - (float)circlewidth, mPaintin);
canvas.drawBitmap(BitmapLock, mFirstMotionX - 25F, mFirstMotionY - 25F, null);
canvas.restore();
invalidate();
if (mMoveFirst == 1)
mMoveFirst = 2;
if (isScreenOn())
mCallback.pokeWakelock();
else
Log.i("LockScreen", "dispatch, screenoff");
} else
{
setBackDrawable();
super.dispatchDraw(canvas);
}
}
public boolean needsInput()
{
return false;
}
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
updateConfiguration();
}
public void onClick2(View view)
{
if (view.getId() != 0x10202c0) goto _L2; else goto _L1
_L1:
mCallPress = true;
mBrowerPress = false;
mCameraPress = false;
mCall.setVisibility(0);
mBrower.setVisibility(4);
mCamera.setVisibility(4);
_L4:
return;
_L2:
if (view.getId() == 0x10202c1)
{
mCallPress = false;
mBrowerPress = true;
mCameraPress = false;
mCall.setVisibility(4);
mBrower.setVisibility(0);
mCamera.setVisibility(4);
} else
if (view.getId() == 0x10202c2)
{
mCallPress = false;
mBrowerPress = false;
mCameraPress = true;
mCall.setVisibility(4);
mBrower.setVisibility(4);
mCamera.setVisibility(0);
}
if (true) goto _L4; else goto _L3
_L3:
}
protected void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
updateConfiguration();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if (i == 82 && mEnableMenuKeyInLockScreen)
mCallback.goToUnlockScreen();
return false;
}
public void onPause()
{
mScreenOn = false;
mTouching = false;
mStatusViewManager.onPause();
setBackDrawable();
if (mDMLock)
mUnlockWidgetMethods.reset(false);
mHDMI.hdmiPortraitEnable(false);
}
public void onPhoneStateChanged(String s)
{
}
public void onResume()
{
mAnimate = false;
mTouching = false;
mMotionDeltaY = 0.0F;
mStatusViewManager.onResume();
postDelayed(mOnResumePing, 500L);
mHDMI.hdmiPortraitEnable(true);
mScreenOn = isScreenOn();
setBackDrawable();
}
public void onRingerModeChanged(int i)
{
boolean flag;
if (2 != i)
flag = true;
else
flag = false;
if (flag != mSilentMode)
{
mSilentMode = flag;
if (mDMLock)
mUnlockWidgetMethods.updateResources();
}
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if (mScreenOn && !mDMLock) goto _L2; else goto _L1
_L1:
boolean flag;
Log.w("LockScreen", " ** Lock Screen is off or animation is running **");
flag = false;
_L8:
return flag;
_L2:
int i;
int j;
int k;
int l;
int i1;
int j1;
int k1;
int l1;
int i2;
i = motionevent.getAction();
j = (int)motionevent.getX();
mUnlock = false;
k = (int)motionevent.getY();
l = mCall.getWidth();
i1 = mCall.getHeight();
j1 = mBrower.getWidth();
k1 = mBrower.getHeight();
l1 = mCamera.getWidth();
i2 = mCamera.getHeight();
mCall.getLocationInWindow(locationCall);
mBrower.getLocationInWindow(locationBrower);
mCamera.getLocationInWindow(locationCamera);
i & 0xff;
JVM INSTR tableswitch 0 2: default 172
// 0 193
// 1 834
// 2 662;
goto _L3 _L4 _L5 _L6
_L5:
break MISSING_BLOCK_LABEL_834;
_L3:
break; /* Loop/switch isn't completed */
_L4:
break; /* Loop/switch isn't completed */
_L9:
if (mUnlock)
mCallback.goToUnlockScreen();
flag = true;
if (true) goto _L8; else goto _L7
_L7:
if (!mAnimate)
{
if (k > locationCall[1] && k < i1 + locationCall[1] && j > locationCall[0] && j < l + locationCall[0])
{
mCallPress = true;
mBrowerPress = false;
mCameraPress = false;
mCall.setVisibility(0);
mBrower.setVisibility(4);
mCamera.setVisibility(4);
mLockString.setText(0x10404db);
} else
if (k > locationBrower[1] && k < k1 + locationBrower[1] && j > locationBrower[0] && j < j1 + locationBrower[0])
{
mCallPress = false;
mBrowerPress = true;
mCameraPress = false;
mCall.setVisibility(4);
mBrower.setVisibility(0);
mCamera.setVisibility(4);
mLockString.setText(0x10404db);
} else
if (k > locationCamera[1] && k < i2 + locationCamera[1] && j > locationCamera[0] && j < l1 + locationCamera[0])
{
mCallPress = false;
mBrowerPress = false;
mCameraPress = true;
mCall.setVisibility(4);
mBrower.setVisibility(4);
mCamera.setVisibility(0);
mLockString.setText(0x10404db);
} else
{
onWallpaperTap(motionevent);
}
playSounds(true);
mFirstMotionX = j;
mFirstMotionY = k;
mMoveFirst2 = true;
m_DrawWaterWave.DropStone(j, k, 10, 50);
if (mMoveFirst == 10)
{
mMoveFirst = 1;
AnimationSet animationset = new AnimationSet(false);
b8 b8_1 = new b8(mFirstMotionX - (float)circlewidth, mFirstMotionY - (float)circlewidth, linearLayout, linearLayout2);
b8_1.initialize(circlewidth, circlewidth, 0, 0);
animationset.addAnimation(b8_1);
linearLayout.startAnimation(animationset);
android.view.animation.Animation.AnimationListener animationlistener = new android.view.animation.Animation.AnimationListener() {
final LockScreen this$0;
public void onAnimationEnd(Animation animation)
{
if (mTouching)
linearLayout2.setVisibility(0);
linearLayout.clearAnimation();
linearLayout.setVisibility(4);
}
public void onAnimationRepeat(Animation animation)
{
}
public void onAnimationStart(Animation animation)
{
}
{
this$0 = LockScreen.this;
super();
}
};
b8_1.setAnimationListener(animationlistener);
}
}
goto _L9
_L6:
if (!mAnimate)
{
mTouching = true;
mMotionDeltaY = (float)k - mFirstMotionY;
mMotionDeltaX = (float)j - mFirstMotionX;
if ((mMotionDeltaX % 3F == 0.0F || mMotionDeltaY % 3F == 0.0F) && mFirstMotionY < 750F)
onWallpaperTap(motionevent);
if (mMoveFirst2 && (mMotionDeltaX >= 20F || mMotionDeltaY >= 20F || mMotionDeltaX <= -20F || mMotionDeltaY <= -20F) && mFirstMotionY < 750F)
mMoveFirst2 = false;
if (mMotionDeltaY <= 0.0F);
m_DrawWaterWave.DropStone(j, k, 10, 50);
}
goto _L9
if (!mAnimate)
{
onWallpaperTap(motionevent);
float f = mMotionDeltaX;
float f1 = mMotionDeltaY;
mTouching = false;
mMotionDeltaY = 0.0F;
mMotionDeltaX = 0.0F;
mMoveFirst = 0;
if ((mCallPress || mBrowerPress || mCameraPress) && k < 700 && mFirstMotionY > 750F)
{
Intent intent = new Intent();
if (mCallPress)
{
intent.setClassName("com.android.contacts", "com.android.contacts.DialtactsActivity");
intent.setAction("android.intent.action.DIAL");
} else
if (mBrowerPress)
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
else
if (mCameraPress)
intent.setClassName("com.android.camera", "com.android.camera.Camera");
intent.setFlags(0x10000000);
mCallback.goToUnlockScreen();
mContext.startActivity(intent);
mUnlock = false;
} else
if (f * f + f1 * f1 > (float)(circlewidth * circlewidth))
{
mUnlock = true;
} else
{
mCall.setVisibility(0);
mBrower.setVisibility(0);
mCamera.setVisibility(0);
mLockString.setText(0x10404a0);
mUnlock = false;
}
imageCircle.setVisibility(8);
}
goto _L9
}
protected void onWallpaperTap(MotionEvent motionevent)
{
motionevent.findPointerIndex(motionevent.getPointerId(0));
Log.d("SlideButton", (new StringBuilder()).append("eee ").append(motionevent).toString());
mWallpaperManager.sendWallpaperTouch(getWindowToken(), motionevent);
}
protected void onWallpaperTapSecondary(MotionEvent motionevent)
{
int i = motionevent.findPointerIndex(motionevent.getPointerId(0));
mWallpaperManager.sendWallpaperCommand(getWindowToken(), "android.wallpaper.secondaryTap", 0 + (int)motionevent.getX(i), 0 + (int)motionevent.getY(i), 0, null);
}
void updateConfiguration()
{
int i;
Configuration configuration;
i = 1;
configuration = getResources().getConfiguration();
if (configuration.orientation == mCreationOrientation) goto _L2; else goto _L1
_L1:
mCallback.recreateMe(configuration);
_L4:
return;
_L2:
if (configuration.hardKeyboardHidden != mKeyboardHidden)
{
mKeyboardHidden = configuration.hardKeyboardHidden;
if (mKeyboardHidden != i)
i = 0;
if (mUpdateMonitor.isKeyguardBypassEnabled() && i != 0)
mCallback.goToUnlockScreen();
}
if (true) goto _L4; else goto _L3
_L3:
}
static
{
LOCKSCREEN_WALLPAPER_DIR = new File("/data/data/com.android.settings/mtk");
LOCKSCREEN_WALLPAPER_FILE = new File(LOCKSCREEN_WALLPAPER_DIR, "lockScreenWallpaper");
}
/*
static boolean access$002(LockScreen lockscreen, boolean flag)
{
lockscreen.mSilentMode = flag;
return flag;
}
*/
enter code here
}
A good rule of thumb is that these decompilers only generate something that resembles java code. There are often syntax/compilation problems, and there's no guarantee that the semantics match that of the original class.
If you want a lossless representation, it's better to use a disassembler to view the bytecode. For dex files, you can use baksmali, dexdump or dedexer.

Images based on Array Values

I have a dice game and I am trying to change the image of the Die that is selected after the dice are rolled to a "Dead Die" image. I have tried everything I can think of and I always end up finding the Value "0" in the Index or something else but never the correct Die.
When the dice is selected it sets it's value to a Negative Number. Example I select 6 it changes the value to -6 and changes the die to the -6 die image
How can I get it to display AND KEEP the "DEAD" image I want.
Here is the area where it gets the Images
//Get the Dice Images
public Integer getImage(int index) {
if (diceValues[index] == 0) {
return letterImages.get(index);
} else {
return diceImages.get((diceValues[index]));
}
}
I have tried changing
return letterImages.get(index);
to every possible combination of everything and when I do get it to change the image it always ends up at "0" or the the current number of dice selected or the some other number that I'm just not sure how it came up with.
Here is the entire DieManager class
package com.mygames.dice;
import java.util.HashMap;
import android.util.Log;
public class DieManager {
// Will return the Indexes of the dice when this is used
public static final int INDEX_FLAG = 1;
// Will return the values of the dice when this is used
public static final int VALUE_FLAG = 2;
// Will return the absolute values of the dice when this is used
public static final int ABS_VALUE_FLAG = 3;
// The array that holds the dice
private int[] diceValues = { 0, 0, 0, 0, 0, 0 };
private HashMap<Integer, Integer> diceImages = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> deadImages = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> letterImages = new HashMap<Integer, Integer>();
// Sets #newValue to dieValues[#index]
public void setValue(int index, int newValue) {
Log.w(getClass().getName(), "Index = " + index + " Value = " + newValue);
diceValues[index] = newValue;
}
public DieManager() {
super();
initializeMaps();
}
private void initializeMaps() {
diceImages.put(-6, R.drawable.die6_select);
diceImages.put(-5, R.drawable.die5_select);
diceImages.put(-4, R.drawable.die4_select);
diceImages.put(-3, R.drawable.die3_select);
diceImages.put(-2, R.drawable.die2_select);
diceImages.put(-1, R.drawable.die1_select);
diceImages.put(1, R.drawable.die1_roll);
diceImages.put(2, R.drawable.die2_roll);
diceImages.put(3, R.drawable.die3_roll);
diceImages.put(4, R.drawable.die4_roll);
diceImages.put(5, R.drawable.die5_roll);
diceImages.put(6, R.drawable.die6_roll);
deadImages.put(-1, R.drawable.die1_dead);
deadImages.put(-2, R.drawable.die2_dead);
deadImages.put(-3, R.drawable.die3_dead);
deadImages.put(-4, R.drawable.die4_dead);
deadImages.put(-5, R.drawable.die5_dead);
deadImages.put(-6, R.drawable.die6_dead);
letterImages.put(0, R.drawable.die_no);
letterImages.put(1, R.drawable.die_no);
letterImages.put(2, R.drawable.die_no);
letterImages.put(3, R.drawable.die_no);
letterImages.put(4, R.drawable.die_no);
letterImages.put(5, R.drawable.die_no);
}
public void rollDice() {
boolean isNewRound = (numOnTable() == 0);
for (int j = 0; j < 6; j++) {
// If its a new round then the dice value can be changed from 0.
// Else it can't
if (isNewRound || diceValues[j] != 0)
diceValues[j] = (int) ((Math.random() * 6) + 1);
}
}
// Returns the value or absolute value
public int getValue(int index, int flag) {
if (flag == ABS_VALUE_FLAG)
return Math.abs(diceValues[index]);
return diceValues[index];
}
// If a dice value is 0 then its a letter
public int numOnTable() {
int count = 6;
for (int i : diceValues) {
if (i == 0)
count--;
}
return count;
}
// Picking up makes the dice value 0
public void pickUp(int[] highlighted) {
for (int i = 0; i < highlighted.length; i++)
diceValues[highlighted[i]] = 0;
}
// A negative value means a die is highlighted
public void toggleHighlight(int index) {
diceValues[index] *= -1;
}
public void clearTable() {
diceValues[0] = 0;
diceValues[1] = 0;
diceValues[2] = 0;
diceValues[3] = 0;
diceValues[4] = 0;
diceValues[5] = 0;
}
// Return the dice that aren't 0
public int[] diceOnTable(int flag) {
if (flag == ABS_VALUE_FLAG) {
int[] array = new int[diceValues.length];
for (int i = 0; i < diceValues.length; i++)
array[i] = Math.abs(diceValues[i]);
return array;
}
return diceValues;
}
//Returns dice that are negative
public int[] getHighlighted(int flag) {
int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
int count = 0;
for (int j = 0; j < 6; j++) {
if (diceValues[j] < 0) {
if (flag == INDEX_FLAG)
dirtyArray[count++] = j;
if (flag == VALUE_FLAG)
dirtyArray[count++] = diceValues[j];
if (flag == ABS_VALUE_FLAG)
dirtyArray[count++] = Math.abs(diceValues[j]);
}
}
int[] cleanArray = new int[count];
//Returns an array of length 0
if (count == 0)
return cleanArray;
System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
return cleanArray;
}
// Finds in dieValues same #value and excludes #index
public int[] findPairs(int index, int flag) {
int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
int count = 0;
for (int j = 0; j < 6; j++) {
if (j != index
&& Math.abs(diceValues[j]) == Math.abs(diceValues[index])) {
if (flag == INDEX_FLAG)
dirtyArray[count++] = j;
if (flag == VALUE_FLAG)
dirtyArray[count++] = diceValues[j];
if (flag == ABS_VALUE_FLAG)
dirtyArray[count++] = Math.abs(diceValues[j]);
}
}
int[] cleanArray = new int[count];
if (count == 0)
return cleanArray;
System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
return cleanArray;
}
//Get the Dice Images
public Integer getImage(int index) {
if (diceValues[index] == 0) {
return letterImages.get(index);
} else {
return diceImages.get((diceValues[index]));
}
}
//Get the Number of dice remaining that are not 0
public int numDiceRemain() {
int counter = 0;
for (int j = 0; j < diceValues.length; j++) {
if (diceValues[j] > 0)
counter++;
}
return counter;
}
}
The dice value can never be zero on a roll because of the following line in your rollDice() method:
diceValues[j] = (int) ((Math.random() * 6) + 1);
And this seems logical to me. Why would the value on a die ever be zero?

Categories

Resources