Program 5
Program 5
Write a program to create an activity with two buttons START and STOP. On
Pressing of the START button, the activity must start the counter by displaying
the numbers from One and the counter must keep on counting until the STOP
button is pressed. Display the counter value in a TextViewcontrol.
activity_main.xml
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="Counter Application"
android:textSize="36dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView android:id="@+id/lbl_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Counter Value"
android:textColor="@color/colorAccent"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/lbl_text" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Stop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_start" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.program5;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View; import
android.widget.Button; import
android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends
AppCompatActivity implements View.OnClickListener
{
TextView lblCounter;
Button btnStart,btnStop;
int counter=0;
Boolean running=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblCounter=(TextView)findViewById(R.id.lbl_text);
btnStart=(Button)findViewById(R.id.btn_start);
btnStop=(Button)findViewById(R.id.btn_stop);
btnStop.setOnClickListener(this);
btnStart.setOnClickListener(this);
}
};
try { Thread.sleep(1000);
}
catch(Exception e) { }
}
}
}
}
Sample Output