can't use findViewById id cannot resolved - java

I can't figured it out in my project.
I already save the .xml, but the findViewById cannot find my Id. All other findViewById are fine, but the error is on the Apple one. I tried to rename the id, but it didn't work. Here is my code
package com.flaternity.fasterbrain;
import android.annotation.SuppressLint;
import com.flaternity.fasterbrain.*;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
public class Game extends ActionBarActivity {
TextView Timer, TEST, Score, GAMEOVER, yourScore, TimerText, TIMEUP;
Button Left, Right, BACKBTN;
ImageView Apple;
int RanSoal, whichTrue = 0, EngSoal;
static int score=0;
static int curGame;//0=Math 1=English
String[] EngTest={
"I __ sick",//0
"I __ Happy yerterday",
"Books __ available in BookStore",
"He __ Games yesterday",
"Minions __ Bananas",
"She __ Books",
"How __ water do you have?",//6
"your __ is Nice",
"__ love Game",
"I am __ than you",
};
String[] Mathtest ={
"2x2=__",//1 [0]
"4:__=4",
"4+5=__",
"5X5=__",
"5X__=45",//5 [4]
"35-5=__",
"5:5=__",
"2-5=__",
"2X(-5)=__",
"2+__=1",//10[9]
"5-5=__",
"2+1=__",
"4:__=8",
"4:2=__",
"3-2=__",//15[14]
"9X4=__",
"10:__=80",
"9X__=36",
"8X4=__",
"3X3=__"//20[19]
};
CountDownTimer timer = new CountDownTimer(3000,1000){
#Override
public void onTick(long millisUntilFinished) {
Timer.setText(""+millisUntilFinished / 1000);
}
#Override
public void onFinish() {
TimeUP();
Timer.setText("0");
}
};
private void MakeSoalMath(){
RanSoal = (int)(Math.random()*19);
TEST.setText(""+Mathtest[RanSoal]);
switch(RanSoal){
case 0:
Left.setText("4");//True
Right.setText("8");
whichTrue = 0;
break;
case 1:
Left.setText("1");//True
Right.setText("4");
whichTrue = 0;
break;
case 2:
Left.setText("9");//True
Right.setText("20");
whichTrue = 0;
break;
case 3:
Left.setText("25");//True
Right.setText("10");
whichTrue = 0;
break;
case 4:
Left.setText("9");//True
Right.setText("5");
whichTrue = 0;
break;
case 5:
Left.setText("30");//True
Right.setText("7");
whichTrue = 0;
break;
case 6:
Left.setText("1");//True
Right.setText("25");
whichTrue = 0;
break;
case 7:
Left.setText("-3");//True
Right.setText("3");
whichTrue = 0;
break;
case 8:
Left.setText("-10");//True
Right.setText("10");
whichTrue = 0;
break;
case 9:
Left.setText("-1");//True
Right.setText("1");
whichTrue = 0;
break;
case 10:
Left.setText("10");
Right.setText("0");//True
whichTrue = 1;
break;
case 11:
Left.setText("-3");
Right.setText("3");//True
whichTrue = 1;
break;
case 12:
Left.setText("2");
Right.setText("1/2");//True
whichTrue = 1;
break;
case 13:
Left.setText("8");
Right.setText("2");//True
whichTrue = 1;
break;
case 14:
Left.setText("3");
Right.setText("1");//True
whichTrue = 1;
break;
case 15:
Left.setText("5");
Right.setText("36");//True
whichTrue = 1;
break;
case 16:
Left.setText("8");
Right.setText("1/8");//True
whichTrue = 1;
break;
case 17:
Left.setText("27");
Right.setText("4");//True
whichTrue = 1;
break;
case 18:
Left.setText("12");
Right.setText("32");//True
whichTrue = 1;
break;
case 19:
Left.setText("6");
Right.setText("9");//True
whichTrue = 1;
break;
}
}
private void Benar(){
if(curGame == 0){
MakeSoalMath();
}
score++;
Score.setText(""+score);
timer.cancel();
timer.start();
}
private void Salah(){
BACKBTN.setVisibility(View.VISIBLE);
yourScore.setVisibility(View.VISIBLE);
GAMEOVER.setVisibility(View.VISIBLE);
Timer.setVisibility(View.INVISIBLE);
TEST.setVisibility(View.INVISIBLE);
Score.setVisibility(View.INVISIBLE);
Left.setVisibility(View.INVISIBLE);
Right.setVisibility(View.INVISIBLE);
TimerText.setVisibility(View.INVISIBLE);
yourScore.setText("your score:" + score);
timer.cancel();
}
private void TimeUP(){
BACKBTN.setVisibility(View.VISIBLE);
yourScore.setVisibility(View.VISIBLE);
TIMEUP.setVisibility(View.VISIBLE);
Timer.setVisibility(View.INVISIBLE);
TEST.setVisibility(View.INVISIBLE);
Score.setVisibility(View.INVISIBLE);
Left.setVisibility(View.INVISIBLE);
Right.setVisibility(View.INVISIBLE);
TimerText.setVisibility(View.INVISIBLE);
yourScore.setText("your score:" + score);
timer.cancel();
}
private void masukGame(){
Timer=(TextView)findViewById(R.id.Timer);
TEST=(TextView)findViewById(R.id.TEST);
Score=(TextView)findViewById(R.id.Score);
Left=(Button)findViewById(R.id.LeftAnswer);
Right=(Button)findViewById(R.id.RightAnswer);
BACKBTN=(Button)findViewById(R.id.BACKTom);
GAMEOVER=(TextView)findViewById(R.id.GAMEOVER);
yourScore=(TextView)findViewById(R.id.yourScore);
TimerText=(TextView)findViewById(R.id.TimeText);
TIMEUP=(TextView)findViewById(R.id.TIMEUP);
Apple=(ImageView)findViewById(R.id.Apple);
BACKBTN.setVisibility(View.INVISIBLE);
GAMEOVER.setVisibility(View.INVISIBLE);
yourScore.setVisibility(View.INVISIBLE);
TIMEUP.setVisibility(View.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
masukGame();
timer.start();
Right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(whichTrue == 1){
Benar();
}else{
Salah();
}
}
});
Left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(whichTrue == 0){
Benar();
}else{
Salah();
}
}
});
BACKBTN.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent myIA = new Intent(Game.this, MainMenu.class);
Game.this.startActivity(myIA);
}
});
//Math
if(curGame==0){
MakeSoalMath();
}else{//ENGLISH
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.flaternity.fasterbrain.Game" >
<TextView
android:id="#+id/Timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:textSize="28sp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/TEST"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:textSize="28sp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/Score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal = "true"
android:textColor="#000000"
android:textSize="28sp"
android:text="0"
/>
<TextView
android:id="#+id/TimeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textSize="28sp"
android:textColor="#000000"
android:text="Time Left:" />
<Button
android:id="#+id/LeftAnswer"
android:layout_width="140dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="80dp"
android:textColor="#000000"
android:textSize="32sp"
/>
<Button
android:id="#+id/RightAnswer"
android:layout_width="140dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="80dp"
android:layout_alignParentRight="true"
android:textColor="#000000"
android:textSize="32sp"
/>
<TextView
android:id="#+id/GAMEOVER"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#000000"
android:textSize="40sp"
android:text="GAME OVER"
/>
<TextView
android:id="#+id/TIMEUP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#000000"
android:textSize="40sp"
android:text="TIME IS UP"
/>
<Button
android:id="#+id/BACKTom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:layout_alignParentBottom="true"
android:layout_marginBottom="5dp"
android:textColor="#000000"
android:textSize="20sp"
android:text="Back"
/>
<TextView
android:id="#+id/yourScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#000000"
android:textSize="28sp"
android:text="your score :"
/>
<ImageView
android:id="#+id/Apple"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal ="true"
android:layout_marginTop="40dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:src="#drawable/Apple" />
</RelativeLayout>
The Error is on Apple=(ImageView)findViewById(R.id.Apple);
but somehow I noticed the difference before the Problem and After the Problem. Before the problem, when I modify th R.java it says error so I have to restore. But After the problem when I modify R.java it says no Error, I was able to save the change. Does my R.java not generate? I do the reserach but I cant fix the problem. Everybody said the manifest, but I dont know what to change. What happned? How to fix this?

Related

Saving data using savedInstanceState

MainActivity.java
package com.jamesvuong.footballscorekeeper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
final int TOUCHDOWN_POINTS = 6;
final int FIELD_GOAL_POINTS = 3;
final int EXTRA_POINT_1_POINT = 1;
final int EXTRA_POINT_2_POINTS = 2;
final int SAFETY_POINTS = 2;
String score_a , score_b;
String TEXT_A , TEXT_B;
int team_a_score;
int team_b_score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
team_a_score = savedInstanceState.getInt(TEXT_A);
team_b_score = savedInstanceState.getInt(TEXT_B);
}
else {
// Probably initialize members with default values for a new instance
team_a_score = 0;
team_b_score = 0;
}
setContentView(R.layout.activity_main);
displayTeamAScore(team_a_score);
displayTeamBScore(team_b_score);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(TEXT_A,team_a_score);
savedInstanceState.putInt(TEXT_B, team_b_score);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
team_a_score = savedInstanceState.getInt(TEXT_A);
team_b_score = savedInstanceState.getInt(TEXT_B);
}
/**
* Update Scores
*/
public void resetScores(View v) {
team_a_score = 0;
team_b_score = 0;
displayTeamAScore(team_a_score);
displayTeamBScore(team_b_score);
}
public void updateTeamScore(View v) {
switch(v.getId()) {
case R.id.team_a_touchdown:
team_a_score += TOUCHDOWN_POINTS;
break;
case R.id.team_a_field_goal:
team_a_score += FIELD_GOAL_POINTS;
break;
case R.id.team_a_extra_point_1:
team_a_score += EXTRA_POINT_1_POINT;
break;
case R.id.team_a_extra_point_2:
team_a_score += EXTRA_POINT_2_POINTS;
break;
case R.id.team_a_safety:
team_a_score += SAFETY_POINTS;
break;
case R.id.team_b_touchdown:
team_b_score += TOUCHDOWN_POINTS;
break;
case R.id.team_b_field_goal:
team_b_score += FIELD_GOAL_POINTS;
break;
case R.id.team_b_extra_point_1:
team_b_score += EXTRA_POINT_1_POINT;
break;
case R.id.team_b_extra_point_2:
team_b_score += EXTRA_POINT_2_POINTS;
break;
case R.id.team_b_safety:
team_b_score += SAFETY_POINTS;
break;
default:
break;
}
displayTeamAScore(team_a_score);
displayTeamBScore(team_b_score);
}
/**
* Display Scores
*/
public void displayTeamAScore(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score);
scoreView.setText(String.valueOf(score));
}
public void displayTeamBScore(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_b_score);
scoreView.setText(String.valueOf(score));
}
}
Activity_main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.jamesvuong.footballscorekeeper.MainActivity">
<LinearLayout
android:id="#+id/score_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/team_a_score_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="6"
android:orientation="vertical">
<TextView
android:id="#+id/team_a_label"
android:text="Team A"
style="#style/TeamLabelStyle"/>
<TextView
android:id="#+id/team_a_score"
android:text="0"
android:saveEnabled="true"
style="#style/ScoreTextStyle"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="-"
android:gravity="center"
android:textStyle="bold"
android:textSize="30sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/team_b_score_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="6"
android:orientation="vertical">
<TextView
android:id="#+id/team_b_label"
android:text="Team B"
style="#style/TeamLabelStyle"/>
<TextView
android:id="#+id/team_b_score"
android:text="0"
android:saveEnabled="true"
style="#style/ScoreTextStyle"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
android:layout_marginBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/scoring_buttons_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:layout_gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/touchdown_container"
style="#style/ScoreTypeButtonContainerStyle">
<Button
android:id="#+id/team_a_touchdown"
style="#style/ScoreButtonStyle"
android:text="+6"
android:onClick="updateTeamScore"/>
<TextView
android:text="Touchdown"
style="#style/ScoreTypeLabelStyle"/>
<Button
android:id="#+id/team_b_touchdown"
style="#style/ScoreButtonStyle"
android:text="+6"
android:onClick="updateTeamScore"/>
</LinearLayout>
<LinearLayout
android:id="#+id/field_goal_container"
style="#style/ScoreTypeButtonContainerStyle">
<Button
android:id="#+id/team_a_field_goal"
style="#style/ScoreButtonStyle"
android:text="+3"
android:onClick="updateTeamScore"/>
<TextView
android:text="Field Goal"
style="#style/ScoreTypeLabelStyle"/>
<Button
android:id="#+id/team_b_field_goal"
style="#style/ScoreButtonStyle"
android:text="+3"
android:onClick="updateTeamScore"/>
</LinearLayout>
<LinearLayout
android:id="#+id/extra_point_container"
style="#style/ScoreTypeButtonContainerStyle">
<Button
android:id="#+id/team_a_extra_point_1"
style="#style/ScoreButtonStyle"
android:text="+1"
android:onClick="updateTeamScore"/>
<Button
android:id="#+id/team_a_extra_point_2"
style="#style/ScoreButtonStyle"
android:text="+2"
android:onClick="updateTeamScore"/>
<TextView
style="#style/ScoreTypeLabelStyle"
android:text="Extra Point" />
<Button
android:id="#+id/team_b_extra_point_1"
style="#style/ScoreButtonStyle"
android:text="+1"
android:onClick="updateTeamScore"/>
<Button
android:id="#+id/team_b_extra_point_2"
style="#style/ScoreButtonStyle"
android:text="+2"
android:onClick="updateTeamScore"/>
</LinearLayout>
<LinearLayout
android:id="#+id/safety_container"
style="#style/ScoreTypeButtonContainerStyle">
<Button
android:id="#+id/team_a_safety"
style="#style/ScoreButtonStyle"
android:text="+2"
android:onClick="updateTeamScore"/>
<TextView
style="#style/ScoreTypeLabelStyle"
android:text="Safety"/>
<Button
android:id="#+id/team_b_safety"
style="#style/ScoreButtonStyle"
android:text="+2"
android:onClick="updateTeamScore"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
android:layout_marginBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#333333"
android:onClick="resetScores"
android:text="Reset"
android:textColor="#FFFFFF" />
</LinearLayout>
</LinearLayout>
I want to save some values, like score of both the team, so that even after the app is killed(not running anymore in background) the scores are saved and can be retained back when the user again opens the app.I have tried using 'savedInstanceState' but its not working. Please help. I am a beginner in android development.
savedInstanceState is used to save the current state of the app during screen rotations, not to save data permanently. SharedPreferences is what you are looking for. Here is an example :
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// save
sharedPreferences.edit()
.putString("key1", "value")
.putInt("key2", 10)
.apply();
// retrieve
String stringValue = sharedPreferences.getString("key1", null);
int intValue = sharedPreferences.getInt("key2", -1);
// null and -1 are default values if not found
if your app has not been killed then u can store values using saveInstanceState/Application class else U have to use Shared-preference or Sqlite/Other ORM.

Change TextView color when SeekBar passes through value

I have 7 TextViews and one SeekBar
I have the following code which is supposed to change the text color as I move the thumb in the SeekBar:
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SeekBar.OnSeekBarChangeListener {
SeekBar sbOne, sbTwo;
SeekBar sbSyst;
TextView tvOne;
TextView tvSOne, tvSTwo, tvSThree, tvSFour, tvSFive, tvSSix, tvSSeven;
NumberPicker npO, npT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sbSyst = (SeekBar) findViewById(R.id.syst_bar);
sbSyst.setOnSeekBarChangeListener(this);
sbOne = (SeekBar) findViewById(R.id.sb1);
sbOne.setOnSeekBarChangeListener(this);
sbTwo = (SeekBar) findViewById(R.id.sb2);
sbTwo.setOnSeekBarChangeListener(this);
tvOne = (TextView) findViewById(R.id.tv1);
tvSOne = (TextView) findViewById(R.id.tvFirst);
tvSTwo = (TextView) findViewById(R.id.tvSecond);
tvSThree = (TextView) findViewById(R.id.tvThird);
tvSFour = (TextView) findViewById(R.id.tvFourth);
tvSFive = (TextView) findViewById(R.id.tvFifth);
tvSSix = (TextView) findViewById(R.id.tvSixth);
tvSSeven = (TextView) findViewById(R.id.tvSeventh);
/*npO = (NumberPicker) findViewById(R.id.np1);
npO.setMinValue(70);
npO.setMaxValue(190);
npO.setWrapSelectorWheel(true);
npO.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// do something here
tvOne.setText(String.valueOf(newVal));
}
});
npT = (NumberPicker) findViewById(R.id.np2);
npT.setMinValue(40);
npT.setMaxValue(100);
npT.setWrapSelectorWheel(true);*/
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
//tvSColor.setBackgroundColor(getColorFromSeekbars());
progress += 70;
switch(seekBar.getId()) {
case R.id.sb1:
//etO.setText(String.valueOf(progress+70));
//npO.setValue(progress+70);
break;
case R.id.sb2:
//etT.setText(String.valueOf(progress+40));
//npT.setValue(progress+40);
break;
case R.id.syst_bar:
tvOne.setText(String.valueOf(progress));
if (progress == 70) {
tvSOne.setTextColor(Color.parseColor("#00996a"));
tvSTwo.setTextColor(Color.WHITE);
tvSThree.setTextColor(Color.WHITE);
tvSFour.setTextColor(Color.WHITE);
tvSFive.setTextColor(Color.WHITE);
tvSSix.setTextColor(Color.WHITE);
tvSSeven.setTextColor(Color.WHITE);
}
else if (progress == 90) {
tvSOne.setTextColor(Color.WHITE);
tvSTwo.setTextColor(Color.parseColor("#00996a"));
tvSThree.setTextColor(Color.WHITE);
tvSFour.setTextColor(Color.WHITE);
tvSFive.setTextColor(Color.WHITE);
tvSSix.setTextColor(Color.WHITE);
tvSSeven.setTextColor(Color.WHITE);
}
else if (progress == 110) {
tvSOne.setTextColor(Color.WHITE);
tvSTwo.setTextColor(Color.WHITE);
tvSThree.setTextColor(Color.parseColor("#00996a"));
tvSFour.setTextColor(Color.WHITE);
tvSFive.setTextColor(Color.WHITE);
tvSSix.setTextColor(Color.WHITE);
tvSSeven.setTextColor(Color.WHITE);
}
else if (progress == 130) {
tvSOne.setTextColor(Color.WHITE);
tvSTwo.setTextColor(Color.WHITE);
tvSThree.setTextColor(Color.WHITE);
tvSFour.setTextColor(Color.parseColor("#00996a"));
tvSFive.setTextColor(Color.WHITE);
tvSSix.setTextColor(Color.WHITE);
tvSSeven.setTextColor(Color.WHITE);
}
else if (progress == 150) {
tvSOne.setTextColor(Color.WHITE);
tvSTwo.setTextColor(Color.WHITE);
tvSThree.setTextColor(Color.WHITE);
tvSFour.setTextColor(Color.WHITE);
tvSFive.setTextColor(Color.parseColor("#00996a"));
tvSSix.setTextColor(Color.WHITE);
tvSSeven.setTextColor(Color.WHITE);
}
else if (progress == 170) {
tvSOne.setTextColor(Color.WHITE);
tvSTwo.setTextColor(Color.WHITE);
tvSThree.setTextColor(Color.WHITE);
tvSFour.setTextColor(Color.WHITE);
tvSFive.setTextColor(Color.WHITE);
tvSSix.setTextColor(Color.parseColor("#00996a"));
tvSSeven.setTextColor(Color.WHITE);
}
else if (progress == 190) {
tvSOne.setTextColor(Color.WHITE);
tvSTwo.setTextColor(Color.WHITE);
tvSThree.setTextColor(Color.WHITE);
tvSFour.setTextColor(Color.WHITE);
tvSFive.setTextColor(Color.WHITE);
tvSSix.setTextColor(Color.WHITE);
tvSSeven.setTextColor(Color.parseColor("#00996a"));
}
//etT.setText(String.valueOf(progress+70));
//npT.setValue(progress+40);
break;
default:
break;
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
//mTrackingText.setText("Tracking on");
}
public void onStopTrackingTouch(SeekBar seekBar) {
//tvOne.setText("Red: " + String.valueOf(progress));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XML:
<LinearLayout
android:id="#+id/refresh_match_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#drawable/background_round"
android:orientation="vertical"
android:visibility="visible"
android:layout_alignParentBottom="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Systolic (top number)"
android:textColor="#ffffff"
android:textSize="20sp" />
<SeekBar
android:id="#+id/syst_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:progress="0"
android:max="190"
android:progressDrawable="#drawable/progress_bar"
android:secondaryProgress="0"
android:thumb="#drawable/thumb_state" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal"
android:visibility="visible"
android:weightSum="14" >
<TextView
android:id="#+id/tvFirst"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="70"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/tvSecond"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="90"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/tvThird"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="110"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/tvFourth"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="130"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/tvFifth"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="150"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/tvSixth"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="170"
android:textColor="#android:color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/tvSeventh"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center_horizontal"
android:text="190"
android:textColor="#android:color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
I am probably not doing it correctly, but as you can see the value of progress is 190 from the image but the third TextView is green and not the last. Any idea how to resolve it?
you should probably change == to >=
updated answer:
in the xml, you have android:max="120", make it android:max="190"
In the above code you have used else if so what happens is that when the first if or any of the else if becomes true then rest of the else if below that are not evaluated.Hence you get the same color. Try using if in all the conditional statements and you will get the desired result.I tested it :)
EDIT: Adding codes to make it more clear
MainActivity.java
package com.abc.def;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity implements
SeekBar.OnSeekBarChangeListener {
SeekBar sb;
TextView tv1, tv2, tv3, tv4, tv5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = (SeekBar) findViewById(R.id.seekBar1);
sb.setOnSeekBarChangeListener(this);
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
tv3 = (TextView) findViewById(R.id.textView3);
tv4 = (TextView) findViewById(R.id.textView4);
tv5 = (TextView) findViewById(R.id.textView5);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage("Wanna go to www.moma.org for more info?");
// add a neutral button to the alert box and assign a click listener
alertbox.setNegativeButton("NOPE!!",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
}
});
alertbox.setPositiveButton("YEAH!!",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
String url = "http://www.moma.org";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
// show it
alertbox.show();
}
return true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
// TODO Auto-generated method stub
switch (seekBar.getId()) {
case R.id.seekBar1:
// tvOne.setText(String.valueOf(progress));
if (progress >= 10) {
tv1.setBackgroundColor(Color.parseColor("#00996a"));
tv2.setBackgroundColor(Color.WHITE);
tv3.setBackgroundColor(Color.WHITE);
tv4.setBackgroundColor(Color.WHITE);
tv5.setBackgroundColor(Color.WHITE);
}if (progress >= 20) {
tv1.setBackgroundColor(Color.WHITE);
tv2.setBackgroundColor(Color.parseColor("#00996a"));
tv3.setBackgroundColor(Color.WHITE);
tv4.setBackgroundColor(Color.WHITE);
tv5.setBackgroundColor(Color.WHITE);
}if (progress >= 40) {
tv1.setBackgroundColor(Color.WHITE);
tv2.setBackgroundColor(Color.WHITE);
tv3.setBackgroundColor(Color.parseColor("#00996a"));
tv4.setBackgroundColor(Color.WHITE);
tv5.setBackgroundColor(Color.WHITE);
}if (progress >= 60) {
tv1.setBackgroundColor(Color.WHITE);
tv2.setBackgroundColor(Color.WHITE);
tv3.setBackgroundColor(Color.WHITE);
tv4.setBackgroundColor(Color.parseColor("#00996a"));
tv5.setBackgroundColor(Color.WHITE);
}if (progress >= 70) {
tv1.setBackgroundColor(Color.WHITE);
tv2.setBackgroundColor(Color.WHITE);
tv3.setBackgroundColor(Color.WHITE);
tv4.setBackgroundColor(Color.WHITE);
tv5.setBackgroundColor(Color.parseColor("#00996a"));
}if (progress >= 80) {
tv1.setBackgroundColor(Color.WHITE);
tv2.setBackgroundColor(Color.WHITE);
tv3.setBackgroundColor(Color.WHITE);
tv4.setBackgroundColor(Color.WHITE);
tv5.setBackgroundColor(Color.parseColor("#00996a"));
}if (progress >= 100) {
tv1.setBackgroundColor(Color.WHITE);
tv2.setBackgroundColor(Color.WHITE);
tv3.setBackgroundColor(Color.WHITE);
tv4.setBackgroundColor(Color.WHITE);
tv5.setBackgroundColor(Color.WHITE);
}
break;
default:
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/verti"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/beach1"
android:baselineAligned="false"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:weightSum="100"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="60"
android:orientation="vertical"
android:weightSum="100" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="200sp"
android:layout_weight="50"
android:background="#android:color/white"
android:text="" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="200sp"
android:layout_marginTop="23dp"
android:layout_weight="50"
android:background="#android:color/darker_gray"
android:text="" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="40"
android:orientation="vertical"
android:weightSum="100" >
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="158dp"
android:layout_marginLeft="15dp"
android:layout_weight="1"
android:background="#FFEE66"
android:text="" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:background="#AABB66"
android:text="" />
<TextView
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:background="#ee1166"
android:text="" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_weight="1"
android:max="100"
android:progress="0"
android:background="#android:color/black"/>
</LinearLayout>
</LinearLayout>

Android digital clock textview timepicker using buttons

I'm newbie Java programmer and newbie Android app developer... and i'm trying to make a simple 24h digital clock acting like a timepicker. I don't want to use the standard TimePicker widget in this case. App should work on Android 2.1+ also.
My clock i supposed look like this 23:59. When the user clicks on the clock rightmost field, buttons ranging from 0 to 9 (placed in the same Fragment) should update this rightmost field. The field should also be highlighted. I accomplished this with
view.setBackgroundResource(R.color.solid_grey);
Other fields should be updated in the same way, with some logic to avoid invalid values of course. Highlighting should be removed from first touched field when user touch another field.
My crappy solution to the problem:
What i did was to make five TextViews, one for each number and one for the colon. I have attached onTouch listeners to the changeable fields in the clock and onClick listeners for the buttons. Then i have some more or less complicated code with viewholders and tagging buttons with viewholder and what not to get all of this to work.
There MUST be a better way to do this! Don't you think?
First i tried to have a single TextView and just check which index in the string representing the clock in the textview, that was clicked. But this didn't work very good with highlighting. The index was also hard to compute with precision since i could not come up with a better idea than to use
(int) event.getX();
inside the OnTouchListener for the clock TextView.
Any ideas on how to accomplish this in the simplest possible way? If not, i have to stick with the butt-ugly hard to maintain code i made (no i won't post it here). :S
Ok, i'll post my own bulky solution here. It might not be pretty but it is working. Feel free to modify it to your liking. Keep in mind that I'm a newbie from Sweden. :P
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The two most significant hex sets the transparency value -->
<color name="timefield_highlight_color">#FF8F8F8F</color>
<color name="timefield_no_highlight_color">#FF000000</color>
</resources>
timepicker_digital_24h.xml
Change the #dimen-stuff to your liking. Include this in your layout, using xml include-tag, wherever you want. DON'T change the id:s of the views.
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/layout_timepicker_digital_24h"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/vertical_margin" >
<TextView
android:id="#+id/textview_time_set_colon_divider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_hour_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/textview_time_set_colon_divider"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_hour_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/textview_time_set_hour_right"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_minute_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/textview_time_set_colon_divider"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_minute_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/textview_time_set_minute_left"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
</RelativeLayout>
<LinearLayout
android:id="#+id/layout_time_buttons_row_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/horizontal_margin_small"
android:layout_marginRight="#dimen/horizontal_margin_small" >
<Button
android:id="#+id/button_1_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="1"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_2_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="2"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_3_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="3"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_time_buttons_row_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/horizontal_margin_small"
android:layout_marginRight="#dimen/horizontal_margin_small" >
<Button
android:id="#+id/button_4_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="4"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_5_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="5"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_6_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="6"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_time_buttons_row_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/horizontal_margin_small"
android:layout_marginRight="#dimen/horizontal_margin_small" >
<Button
android:id="#+id/button_7_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="7"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_8_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="8"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_9_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="9"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</LinearLayout>
<Button
android:id="#+id/button_0_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/vertical_margin_large"
android:layout_marginLeft="#dimen/horizontal_margin"
android:layout_marginRight="#dimen/horizontal_margin"
android:layout_marginTop="#dimen/button_set_time_margin"
android:text="0"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</merge>
Enums.java
package com.example.example.timepicker;
public class Enums {
public static enum TimeField {
HOUR_LEFT, HOUR_RIGHT, MINUTE_LEFT, MINUTE_RIGHT, NONE;
public TimeField nextReal() {
TimeField fields[] = TimeField.values();
int ordinal = this.ordinal(); // incoming field index
switch(ordinal) {
case 0: // HOUR_LEFT
ordinal = 1;
break;
case 1: // HOUR_RIGHT
ordinal = 2;
break;
case 2: // MINUTE_LEFT
ordinal = 3;
break;
case 3: // MINUTE_RIGHT
ordinal = 0;
break;
case 4: // NONE
ordinal = 0;
}
return fields[ordinal];
}
}
}
TimePickerDigital24h.java
(There is a toast-string in this code that you have to define in your strings.xml.)
package com.example.example.timepicker;
import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.example.R;
import com.example.example.timepicker.Enums.TimeField;
public class TimePickerDigital24h implements OnClickListener, OnTouchListener {
private TimeField mTimeFieldToSet = TimeField.HOUR_LEFT;
private TextView mTextViewHourLeft, mTextViewHourRight, mTextViewMinuteLeft, mTextViewMinuteRight;
private Context mContext;
public TimePickerDigital24h (Context context, String hourOfDay, String minute) {
mContext = context;
mTextViewHourLeft = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_hour_left);
mTextViewHourLeft.setText(hourOfDay.substring(0, 1));
mTextViewHourRight = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_hour_right);
mTextViewHourRight.setText(hourOfDay.substring(1, 2));
mTextViewMinuteLeft = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_minute_left);
mTextViewMinuteLeft.setText(minute.substring(0, 1));
mTextViewMinuteRight = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_minute_right);
mTextViewMinuteRight.setText(minute.substring(1, 2));
mTextViewHourLeft.setOnTouchListener(this);
mTextViewHourRight.setOnTouchListener(this);
mTextViewMinuteLeft.setOnTouchListener(this);
mTextViewMinuteRight.setOnTouchListener(this);
this.setTimeFieldHighlight(TimeField.HOUR_LEFT);
Button button0 = (Button) ((Activity) context).findViewById(R.id.button_0_time_set);
button0.setOnClickListener(this);
Button button1 = (Button) ((Activity) context).findViewById(R.id.button_1_time_set);
button1.setOnClickListener(this);
Button button2 = (Button) ((Activity) context).findViewById(R.id.button_2_time_set);
button2.setOnClickListener(this);
Button button3 = (Button) ((Activity) context).findViewById(R.id.button_3_time_set);
button3.setOnClickListener(this);
Button button4 = (Button) ((Activity) context).findViewById(R.id.button_4_time_set);
button4.setOnClickListener(this);
Button button5 = (Button) ((Activity) context).findViewById(R.id.button_5_time_set);
button5.setOnClickListener(this);
Button button6 = (Button) ((Activity) context).findViewById(R.id.button_6_time_set);
button6.setOnClickListener(this);
Button button7 = (Button) ((Activity) context).findViewById(R.id.button_7_time_set);
button7.setOnClickListener(this);
Button button8 = (Button) ((Activity) context).findViewById(R.id.button_8_time_set);
button8.setOnClickListener(this);
Button button9 = (Button) ((Activity) context).findViewById(R.id.button_9_time_set);
button9.setOnClickListener(this);
}
#Override
public boolean onTouch(View view, MotionEvent event) {
switch(view.getId()) {
case R.id.textview_time_set_hour_left:
mTimeFieldToSet = TimeField.HOUR_LEFT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
case R.id.textview_time_set_hour_right:
mTimeFieldToSet = TimeField.HOUR_RIGHT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
case R.id.textview_time_set_minute_left:
mTimeFieldToSet = TimeField.MINUTE_LEFT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
case R.id.textview_time_set_minute_right:
mTimeFieldToSet = TimeField.MINUTE_RIGHT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
}
return false;
}
#Override
public void onClick(View view) {
int valueToSet = 0;
switch(view.getId()) {
case R.id.button_0_time_set:
valueToSet = 0;
break;
case R.id.button_1_time_set:
valueToSet = 1;
break;
case R.id.button_2_time_set:
valueToSet = 2;
break;
case R.id.button_3_time_set:
valueToSet = 3;
break;
case R.id.button_4_time_set:
valueToSet = 4;
break;
case R.id.button_5_time_set:
valueToSet = 5;
break;
case R.id.button_6_time_set:
valueToSet = 6;
break;
case R.id.button_7_time_set:
valueToSet = 7;
break;
case R.id.button_8_time_set:
valueToSet = 8;
break;
case R.id.button_9_time_set:
valueToSet = 9;
break;
}
try {
this.setTimeField(valueToSet);
} catch (UnsupportedOperationException e) {
Toast.makeText(mContext, mContext.getString(R.string.toast_time_set_error), Toast.LENGTH_LONG).show();
//e.printStackTrace();
}
}
// Setter for timefields in the clock time display. Also highlights the correct field.
private void setTimeField (int valueToSet) throws UnsupportedOperationException {
int hourLeft = Integer.parseInt(mTextViewHourLeft.getText().toString());
int hourRight = Integer.parseInt(mTextViewHourRight.getText().toString());
UnsupportedOperationException exception = new UnsupportedOperationException("Input value invalid for this clock field");
setTimeFieldHighlight(mTimeFieldToSet.nextReal());
switch(mTimeFieldToSet) {
case HOUR_LEFT:
if (valueToSet <= 1) {
mTextViewHourLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_RIGHT;
break;
} else if (valueToSet <= 2 && hourRight <= 3) {
mTextViewHourLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_RIGHT;
break;
} else if (valueToSet <= 2 && hourRight >= 4) {
mTextViewHourRight.setText("3");
mTextViewHourLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_RIGHT;
break;
} else {
setTimeFieldHighlight(mTimeFieldToSet);
throw exception;
}
case HOUR_RIGHT:
if (valueToSet <= 3) {
mTextViewHourRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_LEFT;
break;
} else if (valueToSet > 3 && hourLeft <= 1) {
mTextViewHourRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_LEFT;
break;
} else if (valueToSet > 3 && hourLeft >= 2) {
mTextViewHourLeft.setText("1");
mTextViewHourRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_LEFT;
break;
} else {
setTimeFieldHighlight(mTimeFieldToSet);
throw exception;
}
case MINUTE_LEFT:
if (valueToSet <= 5) {
mTextViewMinuteLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_RIGHT;
break;
} else {
setTimeFieldHighlight(mTimeFieldToSet);
throw exception;
}
case MINUTE_RIGHT:
mTextViewMinuteRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_LEFT;
break;
case NONE:
}
}
// Highlighting of the fields in the clock display
private void setTimeFieldHighlight(TimeField field) {
switch(field) {
case HOUR_LEFT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
break;
case HOUR_RIGHT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
break;
case MINUTE_LEFT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
break;
case MINUTE_RIGHT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_highlight_color);
break;
case NONE:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
}
}
public String getHourOfDay() {
String hourOfDay = mTextViewHourLeft.getText().toString()
+ mTextViewHourRight.getText().toString();
return hourOfDay;
}
public String getMinute() {
String minute = mTextViewMinuteLeft.getText().toString()
+ mTextViewMinuteRight.getText().toString();
return minute;
}
}
**Put this code in your Fragment's OnActivityCreated method to instantiate the TimePickerDigital24h object: **
mTimePicker = new TimePickerDigital24h(getActivity(), "23", "59");
You can read back the time set by the user this way:
mTimePicker.getHourOfDay();
mTimePicker.getMinute();
I'm sure the code could be better in many ways. If you guys know how to do this in a much simpler way, please let me know. / TiredDude

Calculator error in java (classes)

I'm trying to make a simple calculator app for android and i'm stuck now. I was planning to make 2 calculators (one basic and the other more advanced, similar to the one built in Windows). The idea was to make it in 3 different classes.
Two classes would contain the "main" code (buttons, layout) and the last one should contain the function which im planning to call (like add, multiply). I managed to finish both calculators in one class but i don't know how to make them call functions from the other class.
PROBLEM: I managed to create the basic calculator and it can call functions from the other class but if i want to add more calculations one after another it wont work right. What I mean is this: Let's say my first number is 1 and my second is 3. It prints the result 4 but if i click add again and put 2 it prints the result 5 instead of 6. Somehow it stores the second variable into the first one and i cannot figure out why :(
Can anyone help me?
Thanks in advance
enter code here
package com.example.simcalc;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainInterface extends Activity implements OnClickListener {
static EditText disp;
static TextView txt1, txt2;
SimFunctions sm;
TextView tx1;
Button btDot, bt1, bt2, bt3, bt4, bt5, bt6, bt7 ,bt8, bt9, bt0, btPlus, btMinus, btDivide, btMult,btEquals, btC;
float num2 =0 , res;
float num1 = 0;
String saveNumber = "";
static char sim ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_interface);
disp = (EditText) findViewById(R.id.enterNumber);
bt1 = (Button) findViewById(R.id.one);
bt2 = (Button) findViewById(R.id.two);
bt3 = (Button) findViewById(R.id.three);
bt4 = (Button) findViewById(R.id.four);
bt5 = (Button) findViewById(R.id.five);
bt6 = (Button) findViewById(R.id.six);
bt7 = (Button) findViewById(R.id.seven);
bt8 = (Button) findViewById(R.id.eight);
bt9 = (Button) findViewById(R.id.nine);
bt0 = (Button) findViewById(R.id.zero);
btPlus = (Button) findViewById(R.id.add);
btMinus = (Button) findViewById(R.id.sub);
btMult = (Button) findViewById(R.id.mult);
btDivide = (Button) findViewById(R.id.div);
btC = (Button) findViewById (R.id.can);
btDot = (Button) findViewById(R.id.decimal);
btEquals = (Button) findViewById(R.id.equal);
txt1 = (TextView) findViewById(R.id.textView1);
txt2 = (TextView) findViewById(R.id.textView2);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
bt5.setOnClickListener(this);
bt6.setOnClickListener(this);
bt7.setOnClickListener(this);
bt8.setOnClickListener(this);
bt9.setOnClickListener(this);
bt0.setOnClickListener(this);
btPlus.setOnClickListener(this);
btMinus.setOnClickListener(this);
btDivide.setOnClickListener(this);
btMult.setOnClickListener(this);
btC.setOnClickListener(this);
btDot.setOnClickListener(this);
btEquals.setOnClickListener(this);
disp.setText("0");
sm = new SimFunctions();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_interface, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.one:
saveNumber += "1";
disp.setText(saveNumber);
break;
case R.id.two:
saveNumber += "2";
disp.setText(saveNumber);
break;
case R.id.three:
saveNumber += "3";
disp.setText(saveNumber);
break;
case R.id.four:
saveNumber += "4";
disp.setText(saveNumber);
break;
case R.id.five:
saveNumber += "5";
disp.setText(saveNumber);
break;
case R.id.six:
saveNumber += "6";
disp.setText(saveNumber);
break;
case R.id.seven:
saveNumber += "7";
disp.setText(saveNumber);
break;
case R.id.eight:
saveNumber += "8";
disp.setText(saveNumber);
break;
case R.id.nine:
saveNumber += "9";
disp.setText(saveNumber);
break;
case R.id.zero:
saveNumber += "0";
disp.setText(saveNumber);
break;
case R.id.decimal:
if (saveNumber.contains(".")){
break;
}
else{
saveNumber += ".";
disp.setText(saveNumber);
break;
}
case R.id.mult:
sim = '*';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.add:
sim = '+';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.div:
sim = '/';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.sub:
sim = '-';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.equal:
sm.equals(num1, saveNumber, sim);
break;
case R.id.can:
saveNumber = "";
disp.setText(saveNumber);
break;
}
}
}
package com.example.simcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SimFunctions extends MainInterface {
public void equals(float num1, String saveNumber, char simbol){
String ds = "";
if ( saveNumber != "") {
try{
num2 = Float.parseFloat(saveNumber);}
catch(NumberFormatException e){
e.printStackTrace();
}
}
else {
num2 = 0;}
switch (simbol){
case ('*'):
res = num1 * num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";
ds = "";
break;
case ('+'):
ds = Float.toString(num1);
txt1.setText(ds);
ds = Float.toString(num2);
txt2.setText(ds);
res = num1 + num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";
ds = "";
break;
case ('/'):
res = num1 / num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";`enter code here`
ds = "";
break;
enter code here
case ('-'):
res = num1 - num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";
ds = "";
break;
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/testBlack"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainInterface" >
<EditText
android:id="#+id/enterNumber"
android:layout_width="match_parent"
android:layout_height="110dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#color/scoreColor"
android:inputType="numberDecimal" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout2"
android:layout_alignParentBottom="true"
android:layout_marginBottom="86dp"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/seven"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="7" />
<Button
android:id="#+id/eight"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="8" />
<Button
android:id="#+id/nine"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="9" />
<Button
android:id="#+id/div"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_alignLeft="#+id/enterNumber"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/four"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="4" />
<Button
android:id="#+id/five"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="5" />
<Button
android:id="#+id/six"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="6" />
<Button
android:id="#+id/mult"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="*" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout2"
android:layout_below="#+id/enterNumber"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/one"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:id="#+id/two"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:id="#+id/three"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="3" />
<Button
android:id="#+id/sub"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/can"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="c" />
<Button
android:id="#+id/zero"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:id="#+id/equal"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="=" />
<Button
android:id="#+id/add"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="+" />
<Button
android:id="#+id/decimal"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="." />
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout3"
android:layout_alignParentLeft="true"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout3"
android:layout_toRightOf="#+id/textView1"
android:text="TextView" />
</RelativeLayout>
You are putting the result of the operation into the global var 'num1'.
The next time you press '+' you overwrite that value with the previous saveNumber value.
So your logic is like this:
1 -> savenumber = 1
+ -> num1 = 1
3 -> savenumber = 3
= -> num2 = savenumber
-> res = num1 + num2
-> num1 = res
+ -> num1 = savenumber = 3
2 -> savenumber = 2
= -> num2 = savenumber
-> res = num1 + num2
= 3 + 2

Android Launcher Shows Calculator activity layout but does nothing

Hi i'm working on a Android Launcher that Shows Calculator activity. It shows the layout fine but does nothing when you click on any of the buttons I need help I have tried everything I can and i'm getting upset! any help would be amazing!!
Calculator.java:
package com.dva.schooltoolshome;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
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 Calculator extends FragmentActivity implements OnClickListener {
private TextView calculatorDisplay;
private static final String DIGITS = "0123456789.";
private Boolean userIsInTheMiddleOfTypingANumber = false;
DecimalFormat df = new DecimalFormat("############");
CalculatorBrain brain;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
brain = new CalculatorBrain();
calculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
findViewById(R.id.buttonClearMemory).setOnClickListener(this);
findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonCos) != null) {
findViewById(R.id.buttonCos).setOnClickListener(this);
}
if (findViewById(R.id.buttonSin) != null) {
findViewById(R.id.buttonSin).setOnClickListener(this);
}
// Another way to hide the window title and actionbar, but only in newer sdk's
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// ActionBar actionBar = getActionBar();
// actionBar.setDisplayShowHomeEnabled(false);
// actionBar.setDisplayShowTitleEnabled(false);
// actionBar.hide();
// }
}
// #Override
public void onClick(View view) {
String buttonPressed = ((Button) view).getText().toString();
// String digits = "0123456789.";
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
calculatorDisplay.append(buttonPressed);
} else {
calculatorDisplay.setText(buttonPressed);
userIsInTheMiddleOfTypingANumber = true;
}
} else {
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
brain.setOperand(Double.parseDouble(calculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
brain.performOperation(buttonPressed);
calculatorDisplay.setText(df.format(brain.getResult()));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", brain.getResult());
outState.putDouble("MEMORY", brain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
brain.setOperand(savedInstanceState.getDouble("OPERAND"));
brain.setMemory(savedInstanceState.getDouble("MEMORY"));
calculatorDisplay.setText(df.format(brain.getResult()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
CalculatorBrain.java:
package com.dva.schooltoolshome;
public class CalculatorBrain {
// 3 + 6 = 9
// 3 & 6 are called the operand.
// The + is called the operator.
// 9 is the result of the operation.
private double operand = 0;
private double waitingOperand = 0;
private String waitingOperator = "";
private double calculatorMemory = 0;
public void setOperand(double operand) {
this.operand = operand;
}
public double getResult() {
return operand;
}
// used on screen orientation change
public void setMemory(double calculatorMemory) {
this.calculatorMemory = calculatorMemory;
}
// used on screen orientation change
public double getMemory() {
return calculatorMemory;
}
public String toString() {
return Double.toString(operand);
}
protected double performOperation(String operator) {
/*
* If you are using Java 7, then you can use switch in place of if statements
*
* switch (operator) {
* case "MC":
* calculatorMemory = 0;
* break;
* case "M+":
* calculatorMemory = calculatorMemory + operand;
* break;
* }
*/
if (operator.equals("MC")) {
calculatorMemory = 0;
} else if (operator.equals("M+")) {
calculatorMemory = calculatorMemory + operand;
} else if (operator.equals("M-")) {
calculatorMemory = calculatorMemory - operand;
} else if (operator.equals("MR")) {
operand = calculatorMemory;
} else if (operator.equals("C")) {
operand = 0;
waitingOperator = "";
waitingOperand = 0;
calculatorMemory = 0;
} else if (operator.equals("Sqrt")) {
operand = Math.sqrt(operand);
} else if (operator.equals("1/x")) {
if (operand != 0) {
operand = 1 / operand;
}
} else if (operator.equals("+/-")) {
operand = -operand;
} else if (operator.equals("sin")) {
operand = Math.sin(operand);
} else if (operator.equals("cos")) {
operand = Math.cos(operand);
} else {
performWaitingOperation();
waitingOperator = operator;
waitingOperand = operand;
}
return operand;
}
protected void performWaitingOperation() {
if (waitingOperator.equals("+")) {
operand = waitingOperand + operand;
} else if (waitingOperator.equals("*")) {
operand = waitingOperand * operand;
} else if (waitingOperator.equals("-")) {
operand = waitingOperand - operand;
} else if (waitingOperator.equals("/")) {
if (operand != 0) {
operand = waitingOperand / operand;
}
}
}
}
activity_calculator.xml:
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:maxLines="1"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1" >
<Button
android:id="#+id/buttonAddToMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="M+" />
<Button
android:id="#+id/buttonSubtractFromMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="M-" />
<Button
android:id="#+id/buttonRecallMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="MR" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout2" >
<Button
android:id="#+id/buttonClear"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="C" />
<Button
android:id="#+id/buttonToggleSign"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="+/-" />
<Button
android:id="#+id/buttonDivide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="/" />
<Button
android:id="#+id/buttonMultiply"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="*" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout3" >
<Button
android:id="#+id/button7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button7" />
<Button
android:id="#+id/button8"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button8" />
<Button
android:id="#+id/button9"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button9" />
<Button
android:id="#+id/buttonSubtract"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="-" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout4" >
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button4" />
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button5" />
<Button
android:id="#+id/button6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button6" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="+" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout5"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout7"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:text="#string/button1" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:text="#string/button2" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".34"
android:text="#string/button3" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button0"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".66"
android:text="#string/button0" />
<Button
android:id="#+id/buttonDecimalPoint"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".34"
android:text="." />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/buttonEquals"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".25"
android:text="=" />
</LinearLayout>
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/wbrowser"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/browser" />
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/wbrowser"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<Button
android:id="#+id/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ImageButton01"
android:layout_centerHorizontal="true"
android:text="Tools" />
<Button
android:id="#+id/buttonClearMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_above="#+id/ImageButton01"
android:layout_alignLeft="#+id/tools"
android:layout_marginBottom="163dp"
android:layout_weight=".25"
android:text="MC" />
</RelativeLayout>
I'm still new to android development so please don't judge
Regards
Rapsong11
First of all use switch statement in OnClick(View v) function for every button.
like this.
public void onClick(View v)
{
case R.Id.button1
// the functionality code goes here
break;
case R.id.button2
break;
}

Categories

Resources