How Do I Pass The Package To RemoteView in Android? - android

Me Doing "edu.sju.BlackJack" Is not causing updates that are later called to occur.
I reference the layout correctly and the calls that are supposed to update it are correct, so what do I put in for the package name?
I should add that my package name according to the manifest is the above.
This is the code I have now which currently doesn't update the screen (or i'm guessing change the value correctly).
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
If that's not it.. would it then be this code?
name.setTextViewText(R.id.Dealer_Total, "0");
Dealer_Total is the id for the TextView that I want to change.. however again the Change is not occurring.
Thanks in advance for any and all assistance.
Here is the whole of my code that i'm talking about, first Playscreen.java
package edu.sju.BlackJack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.*;
public class PlayScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
GameEngine Engine = new GameEngine();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_screen);
TextView TextDealer = (TextView)findViewById(R.id.Dealer_Total);
Engine.setView(TextDealer);
//Set up click listeners for all the buttons
View hitButton = findViewById(R.id.hit_button);
hitButton.setOnClickListener(this);
View standButton = findViewById(R.id.stand_button);
standButton.setOnClickListener(this);
//new preplay button (ML 10/24/10)
View prePlayButton = findViewById(R.id.prePlay_button);
prePlayButton.setOnClickListener(this);
Thread thread = new Thread(Engine);
thread.start();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.prePlay_button:
v.setVisibility(View.GONE);
System.out.println("Working?");
Engine.setGameStart(1);
break;
case R.id.hit_button:
Engine.gameHit(1);
break;
case R.id.stand_button:
Engine.gameStand(1);
break;
}
// More buttons go here (if any) ...
}
}
Now here's the GameEngine Thread
Not the Whole of it, just enough so you get the idea
package edu.sju.BlackJack;
import java.util.Random;
import android.widget.RemoteViews;
import android.widget.TextView;
public class GameEngine implements Runnable {
static int playerCount = 0; //keep record of which cards to change for player when hit is selected
static int dealerCount = 0; //keep record of which cards to change for dealer when dealer hits
static int win = 0; //keeps record of wins (JV 10/01/10)
static int lose = 0; //keeps record of loss (JV 10/01/10)
static int hit = 0; //let's engine know if hit button was selected (0 means it has not)
static int stand = 0; //let's engine know if stand button was selected (0 means it has not)
static int playerTotal = 0; //tells player's total (JV 10/01/10)
static int dealerTotal = 0; //tells dealer's total (JV 10/01/10)
static int playerTurn = 0; //activates buttons so that they do actions when clicked (as it's players turn)
static int startGame = 0; //starts the game when the start game button is pressed
TextView TextDealer;
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
public void run() {
name.setTextViewText(R.id.Dealer_Total, "0");
//main();
}
public void setView(TextView a)
{
TextDealer = a;
}
public void setGameStart(int i)
{
startGame = i;
}
public void gameHit(int i)
{
if(playerTurn == 1)
hit = 1;
}
public void gameStand(int i)
{
if(playerTurn == 1)
stand = 1;
}
public void main()
{//Start Game
Deck mainDeck = new Deck();
fillDeck(mainDeck);
//TextView TextPlayer = (TextView)findViewById(R.id.Player_Total);
//TextDealer.setText("" + dealerTotal);
//TextPlayer.setText("" + playerTotal);
while(true)
{
if(startGame == 1)
{
if(mainDeck.getList().size() < 15){
mainDeck = emptyDeck();
fillDeck(mainDeck);
}
//RESET CARD VIEWS TO DEFAULT
//RESET DEALERCARD AND PLAYERCARD TOTALS TO 0
dealerTotal = 0;
playerTotal = 0;
playerCount = 0;
dealerCount = 0;
//playHand(mainDeck);
}
}
}

Whatever your problem is, I don't think it is what you think it is. If your layout is appearing in the app widget, then the package name is being handled properly. If the update (your setTextViewText() call) is not having an effect, then either R.layout.play_screen does not have R.id.Dealer_Total or you are not sending over a RemoteViews that contains the setTextViewText() instructions.

Related

Android: Changing and limiting button click

having some trouble getting 2 buttons to work.
In the screenshot below, I'm making 2 buttons called NEXT & BACK. And these buttons allows the user to change it from Week 1 to Week 3. When they click NEXT and reach Week , I need the button to disable and not allow them to proceed further since its only a max of 3 weeks. Same thing goes for the BACK button and cycling thru and reaching Week 1. See below also for my code.
http://i.stack.imgur.com/fLazK.jpg
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
final String PREFS_NAME = "MyPrefs";
ViewPager viewPager;
String week1 = "1";
String week2 = "2";
String week3 = "3";
private int[] weekNumbers = {1, 2, 3};
int weekNumberCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Casting variables
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
//////// First startup screen after first time use
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
Intent VirginBoot = new Intent(this, Begin_Program.class);
startActivity(VirginBoot);
// Record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).apply();
}
}
public void settingsButton(View view) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
}
public void NextWeek(View view) {
int weekCounter = 0;
TextView weekNumber = (TextView) findViewById(R.id.week_number_text);
ImageButton LastWeekButton = (ImageButton) findViewById(R.id.LastWeek);
ImageButton NextWeekButton = (ImageButton) findViewById(R.id.NextWeek);
switch (view.getId()) {
case R.id.NextWeek:
if (weekCounter < (weekNumbers.length) - 2) {
weekCounter++;
weekNumber.setText(week2);
if (weekCounter == (weekNumbers.length) - 1) {
weekNumber.setText(week3);
LastWeekButton.setClickable(true);
NextWeekButton.setClickable(false);
}
}
case R.id.LastWeek:
if (weekCounter > weekNumbers.length) {
weekCounter--;
weekNumber.setText(week2);
if (weekCounter == (weekNumbers.length) - 1) {
weekNumber.setText(week1);
NextWeekButton.setClickable(true);
LastWeekButton.setClickable(false);
}
}
break;
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new Day_1();
}
if (arg0 == 1) {
fragment = new Day_2();
}
if (arg0 == 2) {
fragment = new Day_3();
}
if (arg0 == 3) {
fragment = new Day_4();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
}
Maybe I'm looking in the wrong areas but I've tried the links below and they havent worked so far.
How to disable button click?
How to disable button as soon as its clicked
Click Limiting on <button>
First off, you should probably store your buttons as fields in your class instead of finding them each time your functions are called, finding them the first time in the activity onCreate() instead. Then, in the OnClick of your button, you can call setEnabled(false) on that button depending on whether the button should still be enabled.

Closing Android Game After 5 Seconds

I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}

display answer in an maths game in Android

In my game i have a hash button which acts like a submit button. when i press the hash button it displays INCORRECT even if the answer is correct, Do i have to add a different if statement for each position in the array? It displays INCORRECT each expression.
(Sorry i'm a new in this)
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
TextView displayExpression;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(multiArray.length) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
public void hash_Clicked(View v){
if (v.getId()== R.id.hash_button){
// Get the Answer from your EditText
String answer = display.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
}else{
// Tell them how bad they are since they can't solve simple equations!
displayExpression.setText("INCORRECT");
}
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Put break statement after you show that the answer is correct, so that you don't iterate through the remaining answers in your array and compare with current, because if you have a correct answer at say index 0, you are still going through the remaining answers in an array, so your "CORRECT" gets replaced by "INCORRECT".
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
break; //<---add this to exit the loop, because correct answer has been found
}

Using multidimensional-array in Android

Here is my edited code:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
TextView displayExpression;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
}
public void hash_Clicked(View v){
if (v.getId()== R.id.hash_button){
// Get the Answer from your EditText
String answer = display.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayExpression.setText("CORRECT");
}else{
displayExpression.setText("INCORRECT");
}
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
After the user enters the wrong answer and clicks the random generator button (random_gen) again my app closes with an error. Does this have anything to do with the multiArray being created in the onClick method? What would i have to do to resolve this?
EDIT:
Now when i press the hash button it does not display correct, Do i have to add a different if statement for each position?
Your ranGenerate will generate integers from 0 to 3, and your array indexes go from 0 to 2, so if random happens to be 3, you get an exception.
Change the maximal generated integer to 2 with the following:
int random = ranGenerate.nextInt(3); //this generates integers from 0 to 2
or even better - use the length of your array, so that if you add more to it later, you won't have to change the random generation code:
int random = ranGenerate.nextInt(multiArray.length);
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
nextInt(4) can give values range 0 - 3. and your array have values from 0 - 2.
Change to int random = ranGenerate.nextInt(3) or add another item to array.

Android calculator: button for decimal place

I am new to Android development and currently learning to design for a basic calculator app. I have already self designed the layout, but sourced Main Activity codes from different websites for the operations for 0 to 9, +, -, *, / and after incorporation, they work fine.
However, I do want to further modify the MainActivity with decimal point function.
While integer can be shown properly to the screen using "current = current * 10 + number", eg 53 = 5*10+3;
I am thinking applying the same approach for decimal point with a loop function, the idea like this:
1. current = current + remaining if dot button is pressed
2. create an integer i, i increases by 1 once any numerial button is clicked
3. so that when e.g. input 5.3, i =1, it will = 5 + 3/(10^i) = 5.3
4. 5.3 loop to here, then when e.g. input as 5.39, now i=2, it will = 5.3 + 9/(10^i) = 5.39
QUESTION >>
*Yet...really...I am so fresh that I do not know how to design the coding for the decimal button, would there be anyone can suggest the code?* first ignore the following addons where errors to be detected (such as delete the second dot if the dot is input twice or more, adding 0 in front of . if say, .5 is input)
The button id is as follows, and once clicked to refer to DecimalClickEvent
Button b_decimal = (Button) findViewById(R.id.decimal);
b_decimal.setOnClickListener(new DecimalClickEvent(???));}
Many many thanks in advance!! The codes are attached below for reference and your comments:
=========================MainActivity.java=====================================
package com.trial.newcalculator;
import java.io.Serializable;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
#SuppressLint("ParserError")
public class MainActivity extends Activity {
State s;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s = new State();
int[] opNumbers = new int[] {
R.id.zero,
R.id.one,
R.id.two,
R.id.three,
R.id.four,
R.id.five,
R.id.six,
R.id.seven,
R.id.eight,
R.id.nine,
};
final TextView textView = (TextView) findViewById(R.id.ansEditText);
for (int i = 0; i < 10;i++){
final Button button = (Button) findViewById(opNumbers[i]);
button.setOnClickListener(new NumberClickEvent(textView,s,i));
}
int[] opButtons = new int[] { R.id.add, R.id.subtract, R.id.multiply, R.id.divide };
State.Operation[] states = new State.Operation[] {
State.Operation.PLUS,
State.Operation.MINUS,
State.Operation.MULTIPLY,
State.Operation.DIVIDE};
for(int i = 0; i < opButtons.length;i++){
Button b_op = (Button) findViewById(opButtons[i]);
b_op.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
}
// Memory functions
int[] memButtons = new int[] { R.id.MC, R.id.MR, R.id.Mdeduct, R.id.Mplus};
State.Operation[] mstates = new State.Operation[] {
State.Operation.MEMORYCLEAR,
State.Operation.MEMORYCALL,
State.Operation.MEMORYMINUS,
State.Operation.MEMORYPLUS};
for(int i = 0; i < memButtons.length;i++){
Button b_mem = (Button) findViewById(memButtons[i]);
b_mem.setOnClickListener(new OperationClickEvent(textView, s, states[i]));
}
// Memory functions
//decimal
// Button b_decimal = (Button) findViewById(R.id.decimal);
// b_decimal.setOnClickListener(new DecimalClickEvent(textView, s, "."));
//decimal
Button b_eq = (Button) findViewById(R.id.equal);
b_eq.setOnClickListener(new EqualClickEvent(textView, s));
Button b_op = (Button) findViewById(R.id.ac);
b_op.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
s.clear();
textView.setText(s.getDisplay());
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("STATE", s);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Serializable serializable = savedInstanceState.getSerializable("STATE");
if(serializable!= null){
s = (State) serializable;
}
}
public void onPause(){
super.onPause();
}
}
===============================State.java==================================
package com.trial.newcalculator;
import java.io.Serializable;
import android.text.Editable;
import android.widget.TextView;
public class State implements Serializable {
private static final long serialVersionUID = -1231231231231233L;
public TextView output;
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE,
MEMORYPLUS,
MEMORYMINUS,
MEMORYCALL,
MEMORYCLEAR,
}
public enum IOState{
INPUTTING,
DISPLAY_RESULT,
}
private Double accu = null;
private double current = 0;
private double memory = 0;
private Operation currentOp = null;
private IOState currentState = IOState.INPUTTING;
public Operation getCurrentOp() {
return currentOp;
}
public void setCurrentOp(Operation currentOp) {
if (currentState == IOState.INPUTTING){
if (accu != null && this.currentOp != null ){calculateResult();
}
else{accu = Double.valueOf(current);current = 0;
}
}
this.currentOp = currentOp;
if (currentState == IOState.INPUTTING){
currentState = IOState.DISPLAY_RESULT;
}
}
private void calculateResult() {
double res = accu.doubleValue();
switch (currentOp) {
case PLUS:
res += current;
break;
case MINUS:
res -= current;
break;
case MULTIPLY:
res *= current;
break;
case DIVIDE:
res /= current;
break;
case MEMORYPLUS:
memory += current;
break;
case MEMORYMINUS:
memory -= current;
break;
case MEMORYCLEAR:
memory = 0;
break;
case MEMORYCALL:
current = memory;
break;
}
accu = Double.valueOf(res);
current = 0;
}
public void number(int number) {
if (currentState == IOState.INPUTTING){
current = current *10 + number;
}
else if(currentState == IOState.DISPLAY_RESULT){
currentState = IOState.INPUTTING;
current = number;
}
}
public String getDisplay() {
String res;
Double d = getCurrentDisplayValue();
double doubleValue = d.doubleValue();
int intVal = (int)doubleValue;
if (intVal == doubleValue){
res = Integer.toString(intVal);
}
else{
res = d.toString();
}
return res;
}
private Double getCurrentDisplayValue() {
Double d = accu;
if (currentState == IOState.INPUTTING){
d = Double.valueOf(current);
}
return d;
}
public void clear() {
accu = null;
currentState = IOState.INPUTTING;
currentOp = null;
current = 0;
}
public void equal() {
if (accu == null || currentOp == null){
return;
}
calculateResult();
currentState = IOState.DISPLAY_RESULT;
currentOp = null;
current = getCurrentDisplayValue();
}
}
====================OperationClickEvent.java===============================
package com.trial.newcalculator;
import com.trial.newcalculator.State.Operation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class OperationClickEvent implements OnClickListener {
private State s;
private TextView textView;
private Operation op;
public OperationClickEvent(TextView textView, State s, State.Operation op) {
super();
this.op = op;
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.setCurrentOp(op);
textView.setText(s.getDisplay());
}
}
=================EqualClickEvent.java=======================================
package com.trial.newcalculator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class EqualClickEvent implements OnClickListener {
private State s;
private TextView textView;
public EqualClickEvent(TextView textView, State s) {
super();
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.equal();
textView.setText(s.getDisplay());
}
}
======================NumberClickEvent.java==================================
package com.trial.newcalculator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
final class NumberClickEvent implements OnClickListener {
private int number;
private State s;
private TextView textView;
public NumberClickEvent(TextView textView, State s, int number) {
super();
this.number = number;
this.s = s;
this.textView = textView;
}
public void onClick(View v) {
s.number(number);
textView.setText(s.getDisplay());
}
}
Instead of creating new classes for negative click event and doublezeroclickevent, i suggest you to get their id's and do the proper functionality when the particular button is clicked .
Each OnClickListener can be a default anonymous class, that will be triggered only by one button.
So no need to name them "NegativeClickEvent", "DoublezeroClickEvent", etc.
You can keep a boolean variable if the "." was pressed, and accept another one only if not.
If you want a usable calculator, you need a "backspace" button as well. So note that the dot may be deleted. (need to keep track of its placement).
For the leading 0, you can use a simple "if dot was pressed first, insert 0.".
There are many ways to implement what you want, but to keep it simple, just handle the cases you need to handle.
Other ways to implement this may include Double.parseDouble(s) with catch (NumberFormatException e) on each key pressed, or using a double as your buffer, and using the buttons to perform mathematical operations on it directly (such as multiply by 10 and adding the new digit on each button press) - this will ensure input validity without the need to parse String, but it's more complicated to implement.

Categories

Resources