I have 2 Edittext which only accepts numbers.
I want to make sure that the fields are not empty before the submit button is pressed to stop the application from crashing.
These are the 2 edittext fields i have.
EditText weightText = (EditText)findViewById(R.id.WeightText);
EditText heightText = (EditText)findViewById(R.id.Heighttext);
Code:
public class BMI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
}
public void calculateHandler(View view) {
// make sure we handle the click of the calculator button
if (view.getId() == R.id.calculate) {
// get the references to the widgets
EditText weightText = (EditText)findViewById(R.id.WeightText);
EditText heightText = (EditText)findViewById(R.id.Heighttext);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
}
}
private float calculateBMI (float weight, float height) {
return (float)Math.round((weight / (height * height)) * 100) / 100 ;
}
// interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}
You can check that your EditTexts are not empty like below:
weightText.getText().length() != 0 && heightText.getText().length() != 0
And you can use this condition inside the onClick(View) method, which is called when your button is clicked like below:
yourButton.setOnClickListener( new OnClickListener(){
public void onClick(){
if(weightText.getText().length() != 0 && heightText.getText().length() != 0){
//do sth
}
});
The second way, you can create TextWatcher which set to both EditTexts and in onTextChanged() you can check that both EditTexts are not empty like below:
private class YourTextWatcher implements TextWatcher{
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
yourButton.setEnabled(weightText.getText().length() != 0 && heightText.getText().length() != 0)
}
#Override
public void afterTextChanged(Editable editable) {
}
}
you can set this TextWatcher for your EditText like below:
weightText.addTextChangedListener(new YourTextWatcher());
heightText.addTextChangedListener(new YourTextWatcher());
Here is code that your Activity should look like:
public class BMI extends Activity {
EditText weightText;
EditText heightText;
TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
weightText = (EditText) findViewById(R.id.WeightText);
heightText = (EditText) findViewById(R.id.Heighttext);
resultText = (TextView) findViewById(R.id.resultLabel);
Button button = (Button) findViewById(R.id.calulate);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculateHandler();
}
});
}
public void calculateHandler() {
// make sure we handle the click of the calculator button
if (weightText.getText().length() == 0 || heightText.getText().length() == 0) {
return;
}
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
// display toast additionally to example
Toast.makeText(this, bmiValue + " = " + bmiInterpretation, Toast.LENGTH_LONG).show();
}
private float calculateBMI(float weight, float height) {
return (float) Math.round((weight / (height * height)) * 100) / 100;
}
// interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}
Calculate method
public void calculateHandler() {
// make sure we handle the click of the calculator button
if (weightText.getText().toString().trim().length() == 0 || heightText.getText().toString().trim().length() == 0) {
Toast.makeText(this, "Please fill all field by numbers", Toast.LENGTH_LONG).show();
return;
}
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
// display toast additionally to example
}
weightText.getText().toString().isEmpty();
try like this..
String weight = weightText.getText().toString();
String height = heightText.getText().toString();
if((Integer.parseInt(weight)!=null) && (Integer.parseInt(height)!=null)){
//Not an empty
}
else{
//empty
}
Related
It works when I convert from Fahrenheit to Celsius but it doesn't work when I try to convert it back from Celsius into Fahrenheit. I've tried for so many times but it still doesn't work for me.
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.converter_second);
rb_celcius = (RadioButton) findViewById(R.id.radioButton_celcius);
rb_fahrenheit = (RadioButton) findViewById(R.id.radioButton2_fahrenheit);
btn_convert = (Button) findViewById(R.id.button3_convert);
btn_clear = (Button) findViewById(R.id.button5_clear);
edTxt_amount = (EditText) findViewById(R.id.editText_amount);
txtVw_answer = (TextView) findViewById(R.id.textView7_answer);
btn_convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double dblFahrenheit = 0;
double dblCelcius = (5.0 / 9) * (dblFahrenheit - 32);
double dblConvertedTemp = 0;
double dblFahConversion;
if (v == btn_convert) {
if (rb_celcius.isChecked()) {
String strFah = edTxt_amount.getText().toString();
if (!strFah.isEmpty()) {
{
dblFahrenheit = Double.parseDouble(strFah);
}
if (dblFahrenheit <= 212) {
dblConvertedTemp = (5.0 / 9.0) * (dblFahrenheit - 32);
txtVw_answer.setText("The answer is " + dblConvertedTemp);
} if (rb_fahrenheit.isChecked()) {
String strCel = edTxt_amount.getText().toString();
if (!strCel.isEmpty()) {
{
dblCelcius = Double.parseDouble(strCel);
}
if (dblCelcius <= 100) {
dblFahConversion = dblCelcius * (9.0 / 5.0) + 32;
txtVw_answer.setText("The answer is" + dblFahConversion);
}
}
else if (v == btn_clear){
rg_group.clearCheck();
txtVw_answer.setText("");
}
}
}
}
}
}
});
}
}
I can't say if the logic is correct, but from what I see, the braces are all wrong. This is also not the best way of writing this solution, I will leave that to you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.converter_second);
rb_celcius = (RadioButton) findViewById(R.id.radioButton_celcius);
rb_fahrenheit = (RadioButton) findViewById(R.id.radioButton2_fahrenheit);
btn_convert = (Button) findViewById(R.id.button3_convert);
btn_clear = (Button) findViewById(R.id.button5_clear);
edTxt_amount = (EditText) findViewById(R.id.editText_amount);
txtVw_answer = (TextView) findViewById(R.id.textView7_answer);
btn_convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double dblFahrenheit = 0;
double dblCelcius = (5.0 / 9) * (dblFahrenheit - 32);
double dblConvertedTemp = 0;
double dblFahConversion;
if (v == btn_convert) {
if (rb_celcius.isChecked()) {
String strFah = edTxt_amount.getText().toString();
if (!strFah.isEmpty()) {
dblFahrenheit = Double.parseDouble(strFah);
}
if (dblFahrenheit <= 212) {
dblConvertedTemp = (5.0 / 9.0) * (dblFahrenheit - 32);
txtVw_answer.setText("The answer is " + dblConvertedTemp);
}
}
if (rb_fahrenheit.isChecked()) {
String strCel = edTxt_amount.getText().toString();
if (!strCel.isEmpty()) {
dblCelcius = Double.parseDouble(strCel);
}
if (dblCelcius <= 100) {
dblFahConversion = dblCelcius * (9.0 / 5.0) + 32;
txtVw_answer.setText("The answer is" + dblFahConversion);
} else if (v == btn_clear){
rg_group.clearCheck();
txtVw_answer.setText("");
}
}
}
}
}
});
}
Your indentation and use of braces makes it quite hard to see the problem. If I fix the indentation, I get the following code:
public void onClick(View v) {
double dblFahrenheit = 0;
double dblCelcius = (5.0 / 9) * (dblFahrenheit - 32);
double dblConvertedTemp = 0;
double dblFahConversion;
if (v == btn_convert) {
if (rb_celcius.isChecked()) {
String strFah = edTxt_amount.getText().toString();
if (!strFah.isEmpty()) {
{
dblFahrenheit = Double.parseDouble(strFah);
}
if (dblFahrenheit <= 212) {
dblConvertedTemp = (5.0 / 9.0) * (dblFahrenheit - 32);
txtVw_answer.setText("The answer is " + dblConvertedTemp);
}
if (rb_fahrenheit.isChecked()) {
String strCel = edTxt_amount.getText().toString();
if (!strCel.isEmpty()) {
{
dblCelcius = Double.parseDouble(strCel);
}
if (dblCelcius <= 100) {
dblFahConversion = dblCelcius * (9.0 / 5.0) + 32;
txtVw_answer.setText("The answer is" + dblFahConversion);
}
}
else if (v == btn_clear){
rg_group.clearCheck();
txtVw_answer.setText("");
}
}
}
}
}
}
I think it does not work because you check if rb_fahrenheit is checked within the if block that is executed when rb_celcius is checked. Given the fact that these views are radiobuttons, I assume that they reside in the same RadioGroup in which case both radiobuttons have to be checked. This is impossible for a RadioGroup. This explains why the other way around does not work. From the looks of it, the code itself should work.
hello guys I am having this problem. When I enter a score in the editText, I want the app to generate the equivalent in the Textview(w/ red box). But the app crashes with this code.
private void calculateEquivalent(){
double x , y;
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString());
if (x >= y * 0.65){
double equivalent = (Math.round((100 + (72 * (x - y)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
} else {
double equivalent = (Math.round((75 + (23 * (x - y * 0.65)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
}
}
The error is empty string when convert from string to double
In this code
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString());
May be total_score.toString() or editScore.getText().toString() was empty
And what is type of total_score variable
You have a problem when trying to convert empty string to a double. You should check first that the text field is not empty and that it doesn't contain characters by catching NumberFormatException
As the error log suggests, you need to make sure that you have proper values before you start the calculation.
So before calling this function you need to check for below conditions:
try
{
if((total_score.toString() != null && !total_score.toString().isEmpty()) && (editScore.getText().toString()!=null && !editScore.getText().toString().isEmpty()))
{
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString()); //chances of getting a Numberformat exception if entered value is not a number
calculateEquivalent();
}
}
catch(NumberFormatException e)
{
//Toast.makeText(m_context, "You entered a wrong value,Please enter only numeric values", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch(Throwable e)
{
e.printStackTrace();
}
Also in your calculateEquivalent(); method, you need to make sure that value of y should not be zero.
Hope this helps you :)
Hey #callmejeo the main problem with the function you wrote above is that you are coverting "NULL" values into String so one thing you can do is that to HANDLE exception.
private void calculateEquivalent(){
try{
double x , y;
y = Double.valueOf(total_score.toString());
x = Double.valueOf(editScore.getText().toString());
if (x >= y * 0.65){
double equivalent = (Math.round((100 + (72 * (x - y)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
} else {
double equivalent = (Math.round((75 + (23 * (x - y * 0.65)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
}
}
catch(Exception e){
Toast.makeText(this,"Please Enter some value",Toast.LENGTH_LONG).show();
}
}
Thanks a lot guys without your suggestions I probably stuck in this problem :)
and then I've come up with this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student_quiz);
TextWatcher inputTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
calculateEquivalent();
}
};
editScore.addTextChangedListener(inputTextWatcher);
}
private void calculateEquivalent(){
try {
y = Double.parseDouble(total_score);
x = Double.parseDouble(editScore.getText().toString());
if (x >= y * 0.65){
double equivalent = (Math.round((100 + (72 * (x - y)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
} else {
double equivalent = (Math.round((75 + (23 * (x - y * 0.65)) / y)));
String equi = String.valueOf(equivalent);
textEquivalent.setText(equi);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), "Please Enter a Number", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
I need to move circles along a circular path for that i am using Object Animator and Path evaluator.All the information is dynamic means it is changing when i receive response so that total number of circles can be changed at runtime.Here is the 1 part of method where all circles are positioning themselves according to their position on screen that is if user release the touch then this method gets called -:
public void slideDownSetToCenter() {
for (int i = 0; i < leftCurrentRunningAnimation.length; i++) {
Logger.i(TAG, "in slide down animation");
if (leftReadyToMove[i]) {
if (leftUpQueue.contains(i)) {
leftUpQueue.remove(i);
}
leftAngle = leftSlice * ++leftAllCirclesAngles[i];
Logger.i("circle leftAngle points of curve down", String.valueOf(leftAllCirclesAngles[i]));
if (leftAngle > leftAngleTop) {
if (i < leftCurrentRunningAnimation.length - 1) {
leftReadyToMove[i + 1] = true; // set next circle to
// move
}
}
Arrays.fill(leftCurrentRunningAnimation, false);
leftCurrentRunningAnimation[i] = true;
Logger.i(TAG, "leftAngle" + leftAngle);
if (leftReadyToMove[i] == true && leftAngle == leftAngleDownOut) {
leftReadyToMove[i] = false;
leftDownStack.add(i);
}
xPosition = (int) (leftCircleCenterX + leftCircleX * Math.cos(leftAngle));
yPosition = (int) (leftCircleCenterY + leftCircleY * Math.sin(leftAngle));
Path = new AnimatorPath();
Path.moveTo(xPosition, yPosition);
Path.lineTo(xPosition, yPosition);
while (true) {
if (leftAngle == leftAngleDownOut) {
break;
}
leftAngle = leftSlice * ++leftAllCirclesAngles[i];
xPosition = (int) (leftCircleCenterX + leftCircleX * Math.cos(leftAngle));
yPosition = (int) (leftCircleCenterY + leftCircleY * Math.sin(leftAngle));
Path.lineTo(xPosition, yPosition);
Logger.i(TAG, "path.........");
}
slideCircleAnimator = ObjectAnimator.ofObject(DynamicCircleSwipeAnimation.this, "leftButtonLocationDynamic", new PathEvaluator(), Path.getPoints().toArray());
slideCircleAnimator.setInterpolator(linearInterpolator);
slideCircleAnimator.setDuration(500);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
slideCircleAnimator.start();
}
});
}
break;
}
}
Here is the Object animator's animation method -:
public void setLeftButtonLocationDynamic(final PathPoint newLoc) {
for (int i = 0; i < leftCurrentRunningAnimation.length; i++) {
if (leftCurrentRunningAnimation[i] == true) {
Logger.i("current button id", String.valueOf(i));
leftArrayOfButtons[i].setTranslationX(newLoc.mX);
leftArrayOfButtons[i].setTranslationY(newLoc.mY);
break;
}
}
}
Here my animation is not happening in correct way that' why i need to pass my view reference from Object.OfObject() method so that i can get it in setLeftButtonLocationDynamic(final PathPoint newLoc,View v).Is anyone has any idea how can i do this?I searched a lot and tried to develop custom class of ObjectAnimator,ValueAnimator and ProperyViewHolder classes but when i copied it from google open source then i get errors in that.Any help is appreciable?
Here to achieve this i changed the approach to move all circles.Previously, i was using ObjectAnimator to move circles one by one and now i am using Animator set for x position and y position.I play both animation together.
Here is the example -:
public void SlideDownFromRightAnimation() {
int rightArrayOfButtonsLength = rightArrayOfButtons.length;
Logger.i(TAG, "queue " + rightUpQueue.size() + "= stack " + rightDownStack.size());
if (rightUpQueue.size() == rtNumberOfButtons) {
Arrays.fill(rightReadyToMove, false);
rightReadyToMove[0] = true;
rightUpQueue.poll();
} else if (rightDownStack.size() == rtNumberOfButtons) {
rightUpQueue.clear();
for (int i = 0; i < rightArrayOfButtonsLength; i++) {
rightUpQueue.add(rightDownStack.pop());
rightAllCirclesAngles[i] = rightCircleUpOutPosition;
}
Arrays.fill(rightReadyToMove, false);
rightReadyToMove[0] = true;
}
for (int i = 0; i < rightArrayOfButtonsLength; i++) {
Logger.i(TAG, "in slide down animation");
if (rightReadyToMove[i]) {
if (rightUpQueue.contains(rightArrayOfButtons[i].getTag())) {
rightUpQueue.remove(i);
}
rightAngle = rightSlice * --rightAllCirclesAngles[i];
Logger.i("circle rightAngle points of curve down", String.valueOf(rightAllCirclesAngles[i]));
if (rightAngle <= rightAngleTop) {
if (i < rightArrayOfButtonsLength - 1) {
rightReadyToMove[i + 1] = true; // set next circle to
// move
}
}
Logger.i(TAG, "rightAngle" + rightAngle);
if (rightAngle <= rightAngleDownOut) {
rightReadyToMove[i] = false;
rightDownStack.add((Integer)rightArrayOfButtons[i].getTag());
rightAllCirclesAngles[i] = rightCircleDownOutPosition;
rightStartAnimation(rightAngle, null, i);
} else {
double rightAngleNext = rightSlice * rightAllCirclesAngles[i];
if (rightAngleNext <= rightAngleDownOut) {
rightReadyToMove[i] = false;
rightDownStack.add((Integer)rightArrayOfButtons[i].getTag());
}
rightStartAnimation(rightAngle, rightAngleNext, i);
}
}
}
}
and here is the right wheels animation function -:
public void rightStartAnimation(Double rightAngle, Double rightAngleNext, int bttnId) {
xPosition = (int) (rightCircleCenterX + rightCircleX * Math.cos(rightAngle));
yPosition = (int) (rightCircleCenterY + rightCircleY * Math.sin(rightAngle));
if (rightAngleNext != null) {
xPosition = (int) (rightCircleCenterX + rightCircleX * Math.cos(rightAngleNext));
yPosition = (int) (rightCircleCenterY + rightCircleY * Math.sin(rightAngleNext));
}
final ObjectAnimator animation1 = ObjectAnimator.ofFloat(rightArrayOfButtons[bttnId], "x", rightArrayOfButtons[bttnId].getX(), xPosition);
animation1.setDuration(0);
animation1.setInterpolator(linearInterpolator);
final ObjectAnimator animation2 = ObjectAnimator.ofFloat(rightArrayOfButtons[bttnId], "y", rightArrayOfButtons[bttnId].getY(), yPosition);
animation2.setDuration(0);
animation2.setInterpolator(linearInterpolator);
final AnimatorSet set = new AnimatorSet();
set.setInterpolator(linearInterpolator);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
set.playTogether(animation1, animation2);
set.start();
}
});
}
I am using MUPDF Library and i added features for manual zoom in, zoom out , rating, setting brightness. Now i am doing with long press the highlighted text and i have to show the meaning from my database. I am trying to do with two things one is clipboard or emulateShiftHeld the below feature is for only android ICS and JellyBean. Can any body suggest on whether any one thing will work for this feature what i am trying. Because on Long Press i can't able to capture the text. Suggestions will be helpful.
This id my MUPDF Activity:
public void createUI(Bundle savedInstanceState) {
if (core == null)
return;
// Now create the UI.
// First create the document view making use of the ReaderView's internal
// gesture recognition
mDocView = new ReaderView(this) {
private boolean showButtonsDisabled;
public void onLongPress(MotionEvent e) {
selectAndCopyText();
//mDocView.getSelectedItem();
//SelectText(mDocView);
/*emulateShiftHeld(layout);
clipboard =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(clipboard.getText().toString());
//layout.findAll(clipboard.getText().toString());
//ClipMan.setPrimaryClip(clipboard);
//String s = (String) clipboard.getText();
//System.out.println("fsfasd"+ s);
CharSequence pasteData="";
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
pasteData = item.getText();
System.out.println("fsf"+pasteData);*/
//ClipData data = ClipData.newPlainText("", "");
///System.out.println("sdf" + data);
//copyClipboard();
}
#SuppressWarnings("deprecation")
public void selectAndCopyText() {
try {
Method m = WebView.class.getMethod("emulateShiftHeld", Boolean.TYPE);
m.invoke(mDocView, false);
} catch (Exception e) {
e.printStackTrace();
// fallback
KeyEvent shiftPressEvent = new KeyEvent(0,0,
KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
shiftPressEvent.dispatch(this);
}
}
public void startTextSelection() {
try {
WebView.class.getMethod("selectText").invoke(this);
} catch (Exception e) {
try {
WebView.class.getMethod("emulateShiftHeld").invoke(this);
} catch (Exception e1) {
KeyEvent shiftPressEvent = new KeyEvent(0, 0,
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(this);
Toast.makeText(getContext(), R.string.app_name, Toast.LENGTH_LONG).show();
}
}
}
// Stick the document view and the buttons overlay into a parent view
//Embedding my reader view to webview
layout = new WebView(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
layout.setBackgroundResource(R.drawable.tiled_background);
//layout.setBackgroundResource(R.color.canvas);
setContentView(layout);
}
This is my Reader View:
public class ReaderView extends AdapterView<Adapter>
implements GestureDetector.OnGestureListener,
ScaleGestureDetector.OnScaleGestureListener,
Runnable {
private static final int MOVING_DIAGONALLY = 0;
private static final int MOVING_LEFT = 1;
private static final int MOVING_RIGHT = 2;
private static final int MOVING_UP = 3;
private static final int MOVING_DOWN = 4;
private static final int FLING_MARGIN = 100;
private static final int GAP = 20;
private static final int SCROLL_SPEED = 2;
private static final float MIN_SCALE = 1.0f;
private static final float MAX_SCALE = 5.0f;
private Adapter mAdapter;
private int mCurrent; // Adapter's index for the current view
private boolean mResetLayout;
private final SparseArray<View>
mChildViews = new SparseArray<View>(3);
// Shadows the children of the adapter view
// but with more sensible indexing
private final LinkedList<View>
mViewCache = new LinkedList<View>();
private boolean mUserInteracting; // Whether the user is interacting
private boolean mScaling; // Whether the user is currently pinch zooming
private float mScale = 1.0f;
private int mXScroll; // Scroll amounts recorded from events.
private int mYScroll; // and then accounted for in onLayout
private final GestureDetector
mGestureDetector;
private final ScaleGestureDetector
mScaleGestureDetector;
private final Scroller mScroller;
private int mScrollerLastX;
private int mScrollerLastY;
private boolean mScrollDisabled;
public ReaderView(Context context) {
super(context);
mGestureDetector = new GestureDetector(this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mScroller = new Scroller(context);
}
public ReaderView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mScroller = new Scroller(context);
}
public ReaderView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mGestureDetector = new GestureDetector(this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mScroller = new Scroller(context);
}
public int getDisplayedViewIndex(ToggleButton bookmark_page, String index_from) {
if (index_from.equals("bookmark_button")) { System.out.println("View_if" + index_from);
bookmark_page.setBackgroundResource(R.drawable.top3hover);
} else { System.out.println("View_else" + index_from);
bookmark_page.setBackgroundResource(R.drawable.top3);
}
return mCurrent;
}
public void setDisplayedViewIndex(int i) {
if (0 <= i && i < mAdapter.getCount()) {
mCurrent = i;
onMoveToChild(i);
mResetLayout = true;
requestLayout();
}
}
public void moveToNext() {
View v = mChildViews.get(mCurrent+1);
if (v != null)
slideViewOntoScreen(v);
}
public void moveToPrevious() {
View v = mChildViews.get(mCurrent-1);
if (v != null)
slideViewOntoScreen(v);
}
public void resetupChildren() {
for (int i = 0; i < mChildViews.size(); i++)
onChildSetup(mChildViews.keyAt(i), mChildViews.valueAt(i));
}
protected void onChildSetup(int i, View v) {}
protected void onMoveToChild(int i) {}
protected void onSettle(View v) {};
protected void onUnsettle(View v) {};
protected void onNotInUse(View v) {};
public View getDisplayedView() {
return mChildViews.get(mCurrent);
}
public void run() {
if (!mScroller.isFinished()) {
mScroller.computeScrollOffset();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
mXScroll += x - mScrollerLastX;
mYScroll += y - mScrollerLastY;
mScrollerLastX = x;
mScrollerLastY = y;
requestLayout();
post(this);
}
else if (!mUserInteracting) {
// End of an inertial scroll and the user is not interacting.
// The layout is stable
View v = mChildViews.get(mCurrent);
postSettle(v);
}
}
public boolean onDown(MotionEvent arg0) {
mScroller.forceFinished(true);
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (mScrollDisabled)
return true;
View v = mChildViews.get(mCurrent);
if (v != null) {
Rect bounds = getScrollBounds(v);
switch(directionOfTravel(velocityX, velocityY)) {
case MOVING_LEFT:
if (bounds.left >= 0) {
// Fling off to the left bring next view onto screen
View vl = mChildViews.get(mCurrent+1);
if (vl != null) {
slideViewOntoScreen(vl);
return true;
}
}
break;
case MOVING_RIGHT:
if (bounds.right <= 0) {
// Fling off to the right bring previous view onto screen
View vr = mChildViews.get(mCurrent-1);
if (vr != null) {
slideViewOntoScreen(vr);
return true;
}
}
break;
}
mScrollerLastX = mScrollerLastY = 0;
// If the page has been dragged out of bounds then we want to spring back
// nicely. fling jumps back into bounds instantly, so we don't want to use
// fling in that case. On the other hand, we don't want to forgo a fling
// just because of a slightly off-angle drag taking us out of bounds other
// than in the direction of the drag, so we test for out of bounds only
// in the direction of travel.
//
// Also don't fling if out of bounds in any direction by more than fling
// margin
Rect expandedBounds = new Rect(bounds);
expandedBounds.inset(-FLING_MARGIN, -FLING_MARGIN);
if(withinBoundsInDirectionOfTravel(bounds, velocityX, velocityY)
&& expandedBounds.contains(0, 0)) {
mScroller.fling(0, 0, (int)velocityX, (int)velocityY, bounds.left, bounds.right, bounds.top, bounds.bottom);
post(this);
}
}
return true;
}
public void onLongPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
if (!mScrollDisabled) {
mXScroll -= distanceX;
mYScroll -= distanceY;
requestLayout();
}
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
public boolean onScale(ScaleGestureDetector detector) {
float previousScale = mScale;
mScale = Math.min(Math.max(mScale * detector.getScaleFactor(), MIN_SCALE), MAX_SCALE);
float factor = mScale/previousScale;
View v = mChildViews.get(mCurrent);
if (v != null) {
// Work out the focus point relative to the view top left
int viewFocusX = (int)detector.getFocusX() - (v.getLeft() + mXScroll);
int viewFocusY = (int)detector.getFocusY() - (v.getTop() + mYScroll);
// Scroll to maintain the focus point
mXScroll += viewFocusX - viewFocusX * factor;
mYScroll += viewFocusY - viewFocusY * factor;
requestLayout();
}
return true;
}
public boolean onScaleBegin(ScaleGestureDetector detector) {
mScaling = true;
// Ignore any scroll amounts yet to be accounted for: the
// screen is not showing the effect of them, so they can
// only confuse the user
mXScroll = mYScroll = 0;
// Avoid jump at end of scaling by disabling scrolling
// until the next start of gesture
mScrollDisabled = true;
return true;
}
public void onScaleEnd(ScaleGestureDetector detector) {
mScaling = false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//mScaleGestureDetector.onTouchEvent(event);
if (!mScaling)
mGestureDetector.onTouchEvent(event);
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
mUserInteracting = true;
}
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
mScrollDisabled = false;
mUserInteracting = false;
View v = mChildViews.get(mCurrent);
if (v != null) {
if (mScroller.isFinished()) {
// If, at the end of user interaction, there is no
// current inertial scroll in operation then animate
// the view onto screen if necessary
slideViewOntoScreen(v);
}
if (mScroller.isFinished()) {
// If still there is no inertial scroll in operation
// then the layout is stable
postSettle(v);
}
}
}
requestLayout();
return true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int n = getChildCount();
for (int i = 0; i < n; i++)
measureView(getChildAt(i));
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
View cv = mChildViews.get(mCurrent);
Point cvOffset;
if (!mResetLayout) {
// Move to next or previous if current is sufficiently off center
if (cv != null) {
cvOffset = subScreenSizeOffset(cv);
// cv.getRight() may be out of date with the current scale
// so add left to the measured width for the correct position
if (cv.getLeft() + cv.getMeasuredWidth() + cvOffset.x + GAP/2 + mXScroll < getWidth()/2 && mCurrent + 1 < mAdapter.getCount()) {
postUnsettle(cv);
// post to invoke test for end of animation
// where we must set hq area for the new current view
post(this);
mCurrent++;
onMoveToChild(mCurrent);
}
if (cv.getLeft() - cvOffset.x - GAP/2 + mXScroll >= getWidth()/2 && mCurrent > 0) {
postUnsettle(cv);
// post to invoke test for end of animation
// where we must set hq area for the new current view
post(this);
mCurrent--;
onMoveToChild(mCurrent);
}
}
// Remove not needed children and hold them for reuse
int numChildren = mChildViews.size();
int childIndices[] = new int[numChildren];
for (int i = 0; i < numChildren; i++)
childIndices[i] = mChildViews.keyAt(i);
for (int i = 0; i < numChildren; i++) {
int ai = childIndices[i];
if (ai < mCurrent - 1 || ai > mCurrent + 1) {
View v = mChildViews.get(ai);
onNotInUse(v);
mViewCache.add(v);
removeViewInLayout(v);
mChildViews.remove(ai);
}
}
} else {
mResetLayout = false;
mXScroll = mYScroll = 0;
// Remove all children and hold them for reuse
int numChildren = mChildViews.size();
for (int i = 0; i < numChildren; i++) {
View v = mChildViews.valueAt(i);
onNotInUse(v);
mViewCache.add(v);
removeViewInLayout(v);
}
mChildViews.clear();
// post to ensure generation of hq area
post(this);
}
// Ensure current view is present
int cvLeft, cvRight, cvTop, cvBottom;
boolean notPresent = (mChildViews.get(mCurrent) == null);
cv = getOrCreateChild(mCurrent);
// When the view is sub-screen-size in either dimension we
// offset it to center within the screen area, and to keep
// the views spaced out
cvOffset = subScreenSizeOffset(cv);
if (notPresent) {
//Main item not already present. Just place it top left
cvLeft = cvOffset.x;
cvTop = cvOffset.y;
} else {
// Main item already present. Adjust by scroll offsets
cvLeft = cv.getLeft() + mXScroll;
cvTop = cv.getTop() + mYScroll;
}
// Scroll values have been accounted for
mXScroll = mYScroll = 0;
cvRight = cvLeft + cv.getMeasuredWidth();
cvBottom = cvTop + cv.getMeasuredHeight();
if (!mUserInteracting && mScroller.isFinished()) {
Point corr = getCorrection(getScrollBounds(cvLeft, cvTop, cvRight, cvBottom));
cvRight += corr.x;
cvLeft += corr.x;
cvTop += corr.y;
cvBottom += corr.y;
} else if (cv.getMeasuredHeight() <= getHeight()) {
// When the current view is as small as the screen in height, clamp
// it vertically
Point corr = getCorrection(getScrollBounds(cvLeft, cvTop, cvRight, cvBottom));
cvTop += corr.y;
cvBottom += corr.y;
}
cv.layout(cvLeft, cvTop, cvRight, cvBottom);
if (mCurrent > 0) {
View lv = getOrCreateChild(mCurrent - 1);
Point leftOffset = subScreenSizeOffset(lv);
int gap = leftOffset.x + GAP + cvOffset.x;
lv.layout(cvLeft - lv.getMeasuredWidth() - gap,
(cvBottom + cvTop - lv.getMeasuredHeight())/2,
cvLeft - gap,
(cvBottom + cvTop + lv.getMeasuredHeight())/2);
}
if (mCurrent + 1 < mAdapter.getCount()) {
View rv = getOrCreateChild(mCurrent + 1);
Point rightOffset = subScreenSizeOffset(rv);
int gap = cvOffset.x + GAP + rightOffset.x;
rv.layout(cvRight + gap,
(cvBottom + cvTop - rv.getMeasuredHeight())/2,
cvRight + rv.getMeasuredWidth() + gap,
(cvBottom + cvTop + rv.getMeasuredHeight())/2);
}
invalidate();
}
#Override
public Adapter getAdapter() {
return mAdapter;
}
#Override
public View getSelectedView() {
throw new UnsupportedOperationException("Not supported");
}
#Override
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
mChildViews.clear();
removeAllViewsInLayout();
requestLayout();
}
#Override
public void setSelection(int arg0) {
throw new UnsupportedOperationException("Not supported");
}
private View getCached() {
if (mViewCache.size() == 0)
return null;
else
return mViewCache.removeFirst();
}
private View getOrCreateChild(int i) {
View v = mChildViews.get(i);
if (v == null) {
v = mAdapter.getView(i, getCached(), this);
addAndMeasureChild(i, v);
}
onChildSetup(i, v);
return v;
}
private void addAndMeasureChild(int i, View v) {
LayoutParams params = v.getLayoutParams();
if (params == null) {
params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
addViewInLayout(v, 0, params, true);
mChildViews.append(i, v); // Record the view against it's adapter index
measureView(v);
}
private void measureView(View v) {
// See what size the view wants to be
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
// Work out a scale that will fit it to this view
float scale = Math.min((float)getWidth()/(float)v.getMeasuredWidth(),
(float)getHeight()/(float)v.getMeasuredHeight());
// Use the fitting values scaled by our current scale factor
v.measure(View.MeasureSpec.EXACTLY | (int)(v.getMeasuredWidth()*scale*mScale),
View.MeasureSpec.EXACTLY | (int)(v.getMeasuredHeight()*scale*mScale));
}
private Rect getScrollBounds(int left, int top, int right, int bottom) {
int xmin = getWidth() - right;
int xmax = -left;
int ymin = getHeight() - bottom;
int ymax = -top;
// In either dimension, if view smaller than screen then
// constrain it to be central
if (xmin > xmax) xmin = xmax = (xmin + xmax)/2;
if (ymin > ymax) ymin = ymax = (ymin + ymax)/2;
return new Rect(xmin, ymin, xmax, ymax);
}
private Rect getScrollBounds(View v) {
// There can be scroll amounts not yet accounted for in
// onLayout, so add mXScroll and mYScroll to the current
// positions when calculating the bounds.
return getScrollBounds(v.getLeft() + mXScroll,
v.getTop() + mYScroll,
v.getLeft() + v.getMeasuredWidth() + mXScroll,
v.getTop() + v.getMeasuredHeight() + mYScroll);
}
private Point getCorrection(Rect bounds) {
return new Point(Math.min(Math.max(0,bounds.left),bounds.right),
Math.min(Math.max(0,bounds.top),bounds.bottom));
}
private void postSettle(final View v) {
// onSettle and onUnsettle are posted so that the calls
// wont be executed until after the system has performed
// layout.
post (new Runnable() {
public void run () {
onSettle(v);
}
});
}
private void postUnsettle(final View v) {
post (new Runnable() {
public void run () {
onUnsettle(v);
}
});
}
private void slideViewOntoScreen(View v) {
Point corr = getCorrection(getScrollBounds(v));
if (corr.x != 0 || corr.y != 0) {
mScrollerLastX = mScrollerLastY = 0;
mScroller.startScroll(0, 0, corr.x, corr.y, 400);
post(this);
}
}
private Point subScreenSizeOffset(View v) {
return new Point(Math.max((getWidth() - v.getMeasuredWidth())/2, 0),
Math.max((getHeight() - v.getMeasuredHeight())/2, 0));
}
private static int directionOfTravel(float vx, float vy) {
if (Math.abs(vx) > 2 * Math.abs(vy))
return (vx > 0) ? MOVING_RIGHT : MOVING_LEFT;
else if (Math.abs(vy) > 2 * Math.abs(vx))
return (vy > 0) ? MOVING_DOWN : MOVING_UP;
else
return MOVING_DIAGONALLY;
}
private static boolean withinBoundsInDirectionOfTravel(Rect bounds, float vx, float vy) {
switch (directionOfTravel(vx, vy)) {
case MOVING_DIAGONALLY: return bounds.contains(0, 0);
case MOVING_LEFT: return bounds.left <= 0;
case MOVING_RIGHT: return bounds.right >= 0;
case MOVING_UP: return bounds.top <= 0;
case MOVING_DOWN: return bounds.bottom >= 0;
default: throw new NoSuchElementException();
}
}
}
In Reader Class, make localbroadcast and implement it in your main Activity
public void onLongPress(MotionEvent e) {
Intent next = new Intent(StringConstant.SEARCH_WORD);
next.putExtra(StringConstant.DOUBLE_TAP_PDF, "true");
LocalBroadcastManager.getInstance(mContext).sendBroadcast(next);
}
This is your broadcast reciever
private BroadcastReceiver mPdfDoubleClickedReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
Log.e("", "mPdfDoubleClickedReciever called");
hideEditedNotes();
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
boolean success = false;
if (pageView != null)
success = pageView.copySelection();
mTopBarMode = TopBarMode.Main;
// showInfo(success ?
// getString(R.string.copied_to_clipboard)
// : getString(R.string.no_text_selected));
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
selectedClipboardText = "";
selectedClipboardText = (String) clipboard.getText();
// Do task here
}
}
};
So here is my code,
public class GameView extends SurfaceView {
private SurfaceHolder holder;
private GameLoopThread gameLoopThread;
private List<Sprite> sprites = new ArrayList<Sprite>();
private long lastClick;
public int d = 0;
public int color;
TextView tv;
public int score;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int arg2, int height) {
}
});
}
private void createSprites() {
int c = 10;
{
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
for (int b = 1; b <= c; b++) {
int random = (int) Math.ceil(Math.random() * 24);
if (random == 1) {
sprites.add(createSprite(R.drawable.bad1));
} else if (random == 2) {
sprites.add(createSprite(R.drawable.bad2));
} else if (random == 3) {
sprites.add(createSprite(R.drawable.bad3));
} else if (random == 4) {
sprites.add(createSprite(R.drawable.bad4));
} else if (random == 5) {
sprites.add(createSprite(R.drawable.bad5));
} else if (random == 6) {
sprites.add(createSprite(R.drawable.bad6));
} else if (random == 7) {
sprites.add(createSprite(R.drawable.bad7));
} else if (random == 8) {
sprites.add(createSprite(R.drawable.bad8));
} else if (random == 9) {
sprites.add(createSprite(R.drawable.bad9));
} else if (random == 10) {
sprites.add(createSprite(R.drawable.bad10));
} else if (random == 11) {
sprites.add(createSprite(R.drawable.bad11));
} else if (random == 12) {
sprites.add(createSprite(R.drawable.bad12));
} else if (random == 13) {
sprites.add(createSprite(R.drawable.bad13));
} else if (random == 14) {
sprites.add(createSprite(R.drawable.bad14));
} else if (random == 15) {
sprites.add(createSprite(R.drawable.bad15));
} else if (random == 16) {
sprites.add(createSprite(R.drawable.bad16));
} else if (random == 17) {
sprites.add(createSprite(R.drawable.bad17));
} else if (random == 18) {
sprites.add(createSprite(R.drawable.good1));
} else if (random == 19) {
sprites.add(createSprite(R.drawable.good2));
} else if (random == 20) {
sprites.add(createSprite(R.drawable.good3));
} else if (random == 21) {
sprites.add(createSprite(R.drawable.good4));
} else if (random == 22) {
sprites.add(createSprite(R.drawable.good5));
} else if (random == 23) {
sprites.add(createSprite(R.drawable.good6));
} else if (random == 24) {
sprites.add(createSprite(R.drawable.good7));
}
}
}
}
private Sprite createSprite(int resource) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resource);
return new Sprite(this, bmp);
}
#SuppressLint({ "WrongCall", "DrawAllocation" })
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(color);
Paint paint = new Paint();
paint.setColor(Color.CYAN);
canvas.drawText("SCORE " + score, 10, 10, paint);
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
}
// this is the ontouch event to destroy the sprites and make the blood splat
// effect
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 200) {
lastClick = System.currentTimeMillis();
synchronized (getHolder()) {
float x = event.getX();
float y = event.getY();
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isCollition(x, y)) {
{
if ((sprites).equals (R.drawable.bad1))
score = score + 5;
else if ((sprites).equals(R.drawable.bad2))
score = score + 5;
else if ((sprites).equals(R.drawable.bad3))
score = score + 5;
else if ((sprites).equals(R.drawable.bad4))
score = score + 5;
else if ((sprites).equals(R.drawable.bad5))
score = score + 5;
else if ((sprites).equals(R.drawable.bad6))
score = score + 5;
else if ((sprites).equals(R.drawable.bad7))
score = score + 5;
else if ((sprites).equals(R.drawable.bad8))
score = score + 5;
else if ((sprites).equals(R.drawable.bad9))
score = score + 5;
else if ((sprites).equals(R.drawable.bad10))
score = score + 5;
else if ((sprites).equals(R.drawable.bad11))
score = score + 5;
else if ((sprites).equals(R.drawable.bad12))
score = score + 5;
else if ((sprites).equals(R.drawable.bad13))
score = score + 5;
else
score = score - 5;
}
d++;
if (d >= 10) {
d = 0;
createSprites();
}
break;
}
}
}
}
return true;
}
}
What I am trying to do is get,
if ((sprites).equals(R.drawable.bad1))
score = score + 5;
To check to see if somewhere in this code,
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 200) {
lastClick = System.currentTimeMillis();
synchronized (getHolder()) {
float x = event.getX();
float y = event.getY();
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
Holds the value of one of the pics that are being deleted, but I am not sure how to code this properly. I am not sure if I need to place the pics into an array each time the randomizer runs or what but the code is taken from the "edu4java" tutorial from youtube.
I have the program on a loop as you can tell that I can delete the pics on touch and the score was right I just am not sure how to get the,
if ((sprites).equals(R.drawable.bad1))
score = score + 5;
To check to "see" the proper pic string. Do I need to check the array that the code "auto creates"? Is there a way to check and see what the value of a string is? Such as "seeing" what is actually being "held" by "sprite" or "sprites" ?
One problem is that you do not supply the source code for Sprite, but perhaps it looks like the code here? Given the code there, there is no neat solution to your problem with the class as it is.
So, how I would approach solving this problem is to add to each sprite a resource ID:
private Sprite createSprite(int resource) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resource);
return new Sprite(this, bmp, resource);
}
Note that I add the extra resource parameter to the constructor. Furthermore, I would add to the Sprite class a method int Sprite.getResource(), so your collision detection code becomes:
if (sprite.isCollition(x, y))
{
if (sprite.getResource() == R.drawable.bad1)
score = score + 5;
else if (sprite.getResource() == R.drawable.bad2)
score = score + 5;
else ...
}
Note: this code is in no way optimal, but hopefully this will point you in the right direction to discover for yourself a better solution. Here in Stack Overflow we don't throw fishes, we teach people to fish.
You can't compare a bitmap with a resource Id, and actually trying to do it manually your self would end up in quiet exhaustive performance for a simple validation, what i would do and to keep it simple, i would create my own class that extends from Sprite, and in stead of passing the context and bitmap, i would pass the context and resource Id, then within this class i would decode the resource and keep a reference of the resource id, i would override the equal method from Sprites and use the reference used to create the object to do the comparison, this would be my class
public class MySprite extends Sprite{
private int bmpID;
public MySprite(Context context, int bmpID){
this.bmpID = bmpID;
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), bmpID);
super(context, bmp);
}
#Override
public boolean equals(Object o) {
if(!(o instanceof MySprite))return false;
return this.bmpID == MySprite.class.cast(o).getBmpId();
}
public int getBmpId(){
return bmpID;
}
}
This way i keep it as a simple int comparison, and most important you can use it to compare two objects of same bmpID, or something like what u wanted by doing this:
if ((sprites).getBmpId() == R.drawable.bad1))
score = score + 5;
Regards!