Android Studio: how progress bar can fill up based on user input - java

I am using a progress bar sample from Github however I noticed that the progress bar fill is set to a fixed value. For example, if the step count goal is 10 (.java class) the man should be "10" in the .XML
My goal: when the user inputs their goal step count, the "10" should be variable and change depending on user input.
java snippet:
ProgressBar progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", lastStep, stepCounter); //animate only from last known step to current step count
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
lastStep = stepCounter;
XML snippet
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="376dp"
android:layout_height="392dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="10"
android:progress="0"
android:progressDrawable="#drawable/circular" />
EDIT********************EDIT
Sorry maybe my question wasn't clear. To provide an example...if the users step goal is 500. I need the progress bar to fill respectively. Therefore, IF step_count = 250 then progress bar should be half full, IF step_count = 750 then should be 3/4 full. I need the progression to be respective to a variable value.

Set android:indeterminate="false". See this fully implemented code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:minHeight="50dp"
android:minWidth="200dp"
android:max="100"
android:indeterminate="false"
android:progress="0" />
<TextView
android:id="#+id/tView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/pBar"
android:layout_below="#+id/pBar" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Start Progress"
android:layout_below="#+id/tView"/>
public class MainActivity extends AppCompatActivity {
private ProgressBar pgsBar;
private int i = 0;
private TextView txtView;
private Handler hdlr = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pgsBar = (ProgressBar) findViewById(R.id.pBar);
txtView = (TextView) findViewById(R.id.tView);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = pgsBar.getProgress();
new Thread(new Runnable() {
public void run() {
while (i < 100) {
i += 1;
// Update the progress bar and display the current value in text view
hdlr.post(new Runnable() {
public void run() {
pgsBar.setProgress(i);
txtView.setText(i+"/"+pgsBar.getMax());
}
});
try {
// Sleep for 100 milliseconds to show the progress slowly.
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}

Related

Spin ImageView without losing height and width in android studio

i am developing a roulette game for learning while my friend ask me to make spinning wheel shape from circle to oval. after changing shape of ImageView to an oval and trying to rotate ,it's height and width are swapping according to each 90-degree rotation. while height and width should not change as i need, following are codes i am using and screenshot attached
thanks for your time .
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/iframe"
android:layout_centerInParent="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:src="#drawable/wheel2min_300x300"
android:scaleType="fitXY"
android:id="#+id/wheel_image"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="25dp"/>
<ImageView
android:layout_width="50dp"
android:layout_height="40dp"
android:src="#drawable/target_147x300"
android:scaleType="fitXY"
android:id="#+id/wheel_pointer"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"/>
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="press to spin"
android:id="#+id/spin_button"
android:layout_below="#id/iframe"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button button;
int h,w;
CountDownTimer countDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.wheel_image);
button = findViewById(R.id.spin_button);
h=imageView.getHeight();
w = imageView.getWidth();
Random random = new Random();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
// reading random value between 10 to 30
int spin = random.nextInt(20)+10;
// since the wheel has 10 divisions, the
// rotation should be a multiple of
// 360/10 = 36 degrees
spin = spin * 36;
// timer for each degree movement
countDownTimer = new CountDownTimer(spin*20,1) {
#Override
public void onTick(long l) {
// rotate the wheel
float rotation = imageView.getRotation() + 2;
imageView.setRotation(rotation);
}
#Override
public void onFinish() {
// enabling the button again
button.setEnabled(true);
}
}.start();
}
});
}
UI i want even when rotation

setText function does not change the TextView

the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!
I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)
java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play =(Button) findViewById(R.id.button4);
Pause =(Button) findViewById(R.id.button5);
hourstext =(TextView) findViewById(R.id.textView1);
mintext =(TextView) findViewById(R.id.textView2);
sectext =(TextView) findViewById(R.id.textView3);
}
void playb(View v) {
while (!ispause) {
sec = 0 ;
while (sec < 60) {
SystemClock.sleep(1000);
sec++;
sectext.setText(Integer.toString(sec));
Log.d("this", "sec value=" + sec);
}
sec = 0;
min++;
Log.d("this","min value ="+min);
mintext.setText(String.valueOf(min));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="114dp"
android:layout_height="94dp"
android:layout_marginTop="159dp"
android:layout_marginEnd="16dp"
android:layout_x="274dp"
android:layout_y="120dp"
android:gravity="center|center_horizontal"
android:text="00"
android:textSize="40sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:layout_marginTop="116dp"
android:layout_marginEnd="93dp"
android:layout_x="217dp"
android:layout_y="296dp"
android:enabled="false"
android:onClick="playb"
android:text="Pause"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/playbutton"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<Button
android:id="#+id/playbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="70dp"
android:layout_marginTop="116dp"
android:layout_x="63dp"
android:layout_y="293dp"
android:onClick="playb"
android:text="playb"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView2"
android:layout_width="120dp"
android:layout_height="97dp"
android:layout_marginTop="156dp"
android:layout_marginEnd="17dp"
android:layout_x="139dp"
android:layout_y="117dp"
android:gravity="center|center_horizontal"
android:text="00"
android:textSize="40sp"
app:layout_constraintEnd_toStartOf="#+id/textView3"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView1"
android:layout_width="103dp"
android:layout_height="94dp"
android:layout_marginStart="16dp"
android:layout_marginTop="159dp"
android:layout_x="11dp"
android:layout_y="117dp"
android:gravity="center_horizontal|center_vertical"
android:text="00"
android:textSize="40sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
i get no error message ! the app keeps working but no updated textView
i've included my XML Code
It's likely to do with running everything on the main thread. You should never call sleep on the main thread or you will block the UI.
When the button is clicked you should start the counter on a background thread. You will then need to update the TextView on the main thread.
It can be achieved quite easily with RxJava:
private Disposable disposable;
disposable = Observable.interval(1, 1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(value -> {
// Update UI
});
To stop the counter:
disposable.dispose();
If you want make counter up for 60 sec you can use this code
long time=60;
new CountDownTimer(time*1000, 1000)
{
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds : " + (time-millisUntilFinished /1000));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Before trying to fix this problem, let first understand why it happens
CAUSE
When you call View.setText(), Android doesn't actually set the text immediately. It pushes all of these set-text works to a queue on main thread to do LATER whenever it has free time.
Let's try to run this block, you will notice that until this while loop finish, View.setText() will not be done.
void playb(View v) {
min = 0
while (min < 1000000) {
min++
Log.d("this", "min value =$min")
mintext.setText(String.valueOf(min))
}
}
So in your situtation, actually the TextView will still be set, but you will not see the change until the while loop finishes.
SOLUTION
You should move this while loop to another thread, you can simply use an AsyncTask or a HandlerThread for that
Ex. Use a HandlerThread:
void playb() {
// Start a new background thread
HandlerThread thread = new HandlerThread("");
thread.start();
// Obtain the handler of new background thread
Handler handler = new Handler(thread.getLooper());
// Obtain the handler of main thread (UI Thread)
final Handler mainHandler = new Handler(this.getMainLooper());
// Create a runnable and send it to background thread to execute
handler.post(new Runnable() {
public final void run() {
// Do the job
int min = 0;
while(true) {
int sec = 0;
while(sec < 60) {
SystemClock.sleep(1000L);
sec ++;
final int currentSec = sec;
// Send the update-text job to main thread to execute
mainHandler.post(new Runnable() {
public final void run() {
secText.setText(currentSec);
}
});
}
sec = 0;
min++;
final int currentMin = min;
// Send the update-text job to main thread to execute
mainHandler.post(new Runnable() {
public final void run() {
minText.setText(currentMin);
}
});
}
}
});
}

My app crashes after clicking button

When I click the button my app crashes and I have no idea why. I've looked up my code a lot of times but can't seem to find any "major flaws". The purpose of the app is just clicking the button twice as fast as possible and it displays the amount of time needed from the first tap to the second tap. Some sort of reaction thing. I used a timer because I didn't know what else to use.
(Value of start time) - (value of current timer) = (time between first and second click).
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context="com.keklabs.reactiontimer.MainActivity">
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:text="Click below to start!"
android:textColor="#39FF14"
android:textSize="30dp" />
<Button
android:id="#+id/startStopButton"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#000000"
android:text="Start / Stop"
android:textSize="25dp"
android:textColor="#39FF14" />
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private final long startTime = 0;
private final long interval = 100;
private boolean buttonClicked;
private Button startStopButton;
private TextView scoreText;
CountDownTimer timer = new CountDownTimer(30000, 100) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText("kek"); //displayed text is value of starttime (30000) - current value of timer,
} //some sort of reaction game thing
#Override
public void onFinish() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView scoreText = (TextView) findViewById(R.id.scoreText);
Button startStopButton = (Button) findViewById(R.id.startStopButton);
startStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!buttonClicked) {
timer.start();
buttonClicked = true;
}
else {
timer.cancel();
buttonClicked = false;
}
}
});
}
}
EDIT
How do i do it the right way in the line scoreText.setText(startTime - millisUntilFinished); to display startTime-current timer value?
CountDownTimer timer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText(startTime - millisUntilFinished);
}
#Override
public void onFinish() {
}
};
Actually, you are declaring your TextView scoreText twice. One gloabally and other locally. You can replace TextView scoreText = (TextView) findViewById(R.id.scoreText);
to scoreText = (TextView) findViewById(R.id.scoreText);
in your onCreate()

Android media player with list view and service

I have implemented an Android media player that is clicking on songs text view will display the layout. The layout displayed with play pause .. and clicking on play stop works well. Here I am thinking in users perspective to implement the below.
Clicking on songs text view should display the songs in list view and in the bottom of the layout small controls should display with play pause and stop
It should play even when other application is opened.
To achieve the point 2 I used media player service and for point 1, I used a `ListView' but not successfully implemented. Below is the code which play the song and and go till end. From this point can anyone please help me to implement list view songs with service?
public class Songs extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2000, backwardTime = 2000;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
private Context context;
private int getCurrentPos=0;
private int[] songs={R.raw.sample_song,R.raw.sleepaway};
#Override
protected void onCreate(Bundle savedInstanceState) {
context=getApplicationContext();
super.onCreate(savedInstanceState);
setContentView(R.layout.mediaplayer);
initializeViews();
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, songs[getCurrentPos]);
mediaPlayer.setLooping(true);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Sample_Song.mp3");
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
// play mp3 song
public void play(View view) {
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = finalTime - timeElapsed;
// duration.setText(String.format("%d min, %d sec", 12, TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - 12));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// Go to next song
public void next(View view) throws IOException{
try {
mediaPlayer.reset();
mediaPlayer = MediaPlayer.create(this, songs[getSongPosition()]);
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private int getSongPosition(){
if(getCurrentPos==songs.length-1){
getCurrentPos=0;
}else if(getCurrentPos==0){
getCurrentPos=getCurrentPos+1;
}else{
getCurrentPos=getCurrentPos+1;
}
return getCurrentPos;
}
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#333333"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/songName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="songName" />
<ImageView
android:id="#+id/mp3Image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:padding="30dp"
android:src="#drawable/music"
android:background="#ffffff"
android:layout_margin="30dp" />
<TextView
android:id="#+id/songDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="songDuration" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/media_rew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:onClick="rewind"
android:src="#android:drawable/ic_media_rew" />
<ImageButton
android:id="#+id/media_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:onClick="pause"
android:src="#android:drawable/ic_media_pause" />
<ImageButton
android:id="#+id/media_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:onClick="play"
android:src="#android:drawable/ic_media_play" />
<ImageButton
android:id="#+id/media_ff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:onClick="forward"
android:src="#android:drawable/ic_media_ff" />
<ImageButton
android:id="#+id/media_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:onClick="next"
android:src="#android:drawable/ic_media_next" />
</LinearLayout>
</LinearLayout>

TextView isn't updating in Android

I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}

Categories