Countdown progress bar in Android Studio - java

I'm trying to make a countdown timer in form of a progress bar, and that's what i tried so far: but it don't work at all.
Layout XML File:
<androidx.constraintlayout.widget.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"
android:background="#drawable/background"
tools:context=".thetest">
<ProgressBar
android:id="#+id/progressBarToday"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="79dp"
android:layout_height="101dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:max="30"
android:progress="29"
android:progressDrawable="#drawable/circular_progress_bar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Java:
public class thetest extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thetest);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBarToday);
Animation an = new RotateAnimation(0.0f, 90.0f, 250f, 273f);
an.setFillAfter(true);
pb.startAnimation(an);
}
}
And finally the drawable style file(not sure if it might help but yeah):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#android:id/progress">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="7.0"
android:useLevel="true">
<gradient
android:startColor="#fb0000"
android:endColor="#00FF00"
android:centerColor="#fbf400"
android:type="sweep" />
</shape>
</item>
</layer-list>

I found the solution:
Xml:
<ProgressBar
android:id="#+id/progressbar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Java code:
public class thetest extends AppCompatActivity {
ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thetest);
mProgressBar=findViewById(R.id.progressbar);
mProgressBar.setProgress(i);
mCountDownTimer=new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
i++;
mProgressBar.setProgress((int)i*100/(30000/1000));
}
#Override
public void onFinish() {
//Do what you want
i++;
mProgressBar.setProgress(100);
}
};
mCountDownTimer.start();
}
}

Rather than using animation to get a countdown timer, you can programmatically set the countdown time length as maximum progress of ProgressBar, and use a Handler object scheduled to run every second, to update the current progress of the ProgressBar as shown below:
final ProgressBar pb = findViewById(R.id.progressBarToday);
// for eg: if countdown is to go for 30 seconds
pb.setMax(30);
// the progress in our progressbar decreases with the decrement
// in the remaining time for countdown to be over
pb.setProgress(30);
// keep track of current progress
final int[] currentProgress = {30};
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
currentProgress[0] -= 1;
pb.setProgress(currentProgress[0]);
if(currentProgress[0] != 0){
new Handler().postDelayed(this, 1000);
}else
Toast.makeText(requireContext(), "Count Down is OVER!!", Toast.LENGTH_LONG).show();
}
}, 1000);

Related

Change background colors between two layouts?

I have activity_main.xml with two Layouts:
<?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"
android:background="#color/appColor">
<android.support.constraint.ConstraintLayout
android:id="#+id/loading_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/appColor">
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="#+id/imageView"
app:layout_constraintStart_toStartOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/imageView"
android:indeterminateTint="#color/white"
android:indeterminateTintMode="src_in"/>
</android.support.constraint.ConstraintLayout>
<android.support.constraint.ConstraintLayout
android:id="#+id/webview_layout"
android:visibility="gone"
android:background="#color/appColor"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/appColor"/>
</android.support.constraint.ConstraintLayout>
First I show the loading_layout and when I finish loading the app shows the webview_layout:
ConstraintLayout loadingLayout;
ConstraintLayout webviewLayout;
WebView webview;
String kAppUrl = "*******";
String kDefaultAppUrl = "******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
loadingLayout = (ConstraintLayout)findViewById(R.id.loading_layout);
webviewLayout = (ConstraintLayout)findViewById(R.id.webview_layout);
webview = (WebView)findViewById(R.id.webView);
webview.clearCache(true);
webview.clearHistory();
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
startLoadingUrlFromServer();
}
private void startLoadingUrlFromServer() {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, kAppUrl,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finishLoadindDataFromServerWithData(response);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
openWebSite(null);
}
});
}
});
queue.add(stringRequest);
}
private void finishLoadindDataFromServerWithData(String response) {
if (response == null || response.equals("")) {
openWebSite(null);
return;
}
if (!response.startsWith("http://") && !response.startsWith("https://")) {
openWebSite(null);
return;
}
openWebSite(response);
}
private void openWebSite(String url) {
loadingLayout.setVisibility(View.GONE);
webviewLayout.setVisibility(View.VISIBLE);
if (url == null || url.equals("")) {
webview.loadUrl(kDefaultAppUrl);
} else {
webview.loadUrl(url);
}
}
The problem that when I set the Visibility of loadingLayout to GONE and the webviewLayout to VISIBLE the app has a white background for two seconds, Any idea how I can change this background color?
It looks like the color you are finding for two seconds is the application theme background.
Go to your AndroidManifest.xml file and open the theme your Application tag is having (if another theme is defined in Activity tag, open that).
This should open your styles.xml file. Add new item for windowBackground to your AppTheme (Assuming this is your theme name), This will change the white background color to the defined one (in below code, its black).
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">#android:color/black</item>
...
..
.
</style>
</resources>

How to have a One Common ProgressBar in Android Project

I'm currently trying to sort out a way to have a single Common ProgressBar to everywhere(Activity/Fragment) I need in my Android Project. The methods I tried did not promise me good results. Please help me to find a better solution. An example with code for android java is more than welcome.
This is my Custom ProgressBar
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fl_common_probar"
android:elevation="40dp"
android:visibility="gone"
android:layout_centerInParent="true">
<View
android:id="#+id/background_dim_pro"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.5"
android:background="#color/textTitleW"
android:elevation="50dp"/>
<RelativeLayout
android:id="#+id/relative_container_pro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:elevation="60dp">
<ImageView
android:id="#+id/image_test"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:src="#drawable/logo_loading" />
<ProgressBar
android:id="#+id/progress_bar_circle_pro"
style="?android:attr/progressBarStyle"
android:layout_width="132dp"
android:layout_height="132dp"
android:indeterminateDrawable="#drawable/circular_progress_bar"
android:indeterminateDuration="#android:integer/config_longAnimTime" />
</RelativeLayout>
Please try with below approach.
1.) Create a layout xml file (dialog_progress.xml) with the below content.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl_progress"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
2.) Create AppUtil Java class and create a static method as below.
public class AppUtil {
// progress bar handling
public static Dialog showProgress(Activity activity) {
Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(0));
dialog.setContentView(R.layout.dialog_progress);
ProgressBar progressBar = dialog.findViewById(R.id.progressBar);
progressBar.getIndeterminateDrawable().setColorFilter(activity.getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
dialog.setCancelable(false);
dialog.show();
return dialog;
}
}
3.) When you need to show a ProgressBar in an Activity/Fragment do as below.
Dialog dialog = AppUtil.showProgress(MainActivity.this);
When you need to dissmiss the progressBar
dialog.dismiss();
That's it. Try and let me know your feedback.
Thank you.
Create a Java class Seperately for Progress Dialog
public class ProgressDialog {
private Dialog dialog;
private ProgressBar progressBar;
public ProgressDialog(Context context) {
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progress_layout);
dialog.setCancelable(false);
if (dialog.getWindow() != null) {
dialog.getWindow()
.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
progressBar = dialog.findViewById(R.id.progressBar);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.getIndeterminateDrawable().setColorFilter(randomColor(), PorterDuff.Mode.MULTIPLY);
new Handler().postDelayed(this, 300);
}
}, 0);
}
public void showDialog() {
if (dialog != null && !dialog.isShowing())
dialog.show();
}
public void hideDialog() {
if (dialog != null && dialog.isShowing())
dialog.cancel();
}}
//Now you can use it in anywhere in you activity/fragment
Activity:
public class ShowProgressBar extends AppCompatActivity{
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_web_pages);
progressDialog= new ProgressDialog (ShowProgressBar.this);
}
//Use these methods in your code where you want to show the progress dialog or hide the dialog.
// showing animated dialog
public void showDialog(){
progressDialog.showDialog();
}
// hide animated dialog
public void hideDialog(){
progressDialog.hideDialog();
}

Android Progress Bar not working

I have made a progress bar in Android but it is not at all working. What am I doing wrong? I have just started to learn android. Below is my code.
MainActivity.java-
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int mporgress=0;
EditText time;
private Handler mHandler = new Handler();
private static final int PROGRESS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Startbuttononclick(View view){
Button startbutton=(Button) findViewById(R.id.button);
startbutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mporgress = Integer.parseInt(time.getText().toString());
progressBar.setProgress(mporgress);
new Thread(new Runnable() {
public void run() {
while (mporgress < 100) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mporgress);
mporgress = doWork();
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
});
}
}
}).start();
}
});
}
public void doprogress(View view) {
}
public int doWork(){
mporgress++;
return mporgress;
}
}
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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.progressbar.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the time:"
android:inputType="number"
android:id="#+id/editText" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="500dp"
android:layout_height="200dp"
android:id="#+id/progressBar4"
android:layout_gravity="center"
android:scrollbarSize="500dp" />
<Button
android:text="START"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_gravity="center"
android:onClick="Startbuttononclick" />
</LinearLayout>
Check out this image below-
- https://i.stack.imgur.com/2TBIb.png
Note- Enter the time in this image is an EditText with a hint and not a TextView.
It is appearing but not working.
I have done these changes so far.-
https://i.stack.imgur.com/UujpB.png
But still the progress bar is still continuously rotating.
Seems you forgot to initialize EditText -time and ProgressBar. Init it inside onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar =(ProgressBar) findViewById(R.id.progressBar4);
time = (EditText) findViewById(R.id.editText); //here
}
Also inside button click the bar:
progressBar = new ProgressBar(this);
mporgress = Integer.parseInt(time.getText().toString());
................
.............

Android animation fade in / fade out is not setting the visibility of the view in the callback function

I have android view that I want to fadeIn and Fadeout when users click on a button. The animation itself is being called and the callback is being called but when the animation triggers the view cannot be seen. I think the problem is with the xml layout, I have been stuck on this for hours if someone can help it would be greatly appreciated.
My Main Layout: - Just view in question
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="left|top"
android:background="#color/whiteOverlay"
android:gravity="center_vertical|center_horizontal"
android:id="#+id/uploadOptions"
android:alpha="0"
android:visibility="gone">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="40dp"
android:paddingRight="40dp">
<Button
style = "#style/basic_button"
android:text="#string/selectFromGallery"
android:id="#+id/gallery_select"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
style = "#style/basic_button"
android:text="#string/selectFromCamera"
android:id="#+id/camera_select"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</LinearLayout>
FadeIn
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:duration="500" />
</set>
FadeOut
<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:interpolator="#android:anim/accelerate_interpolator"
android:duration="500" />
</set>
Activity Java -
public class regPP extends Activity {
private String lang = "";
private Boolean optionsActive = false;
private LinearLayout options = null;
private void fade (final View view, final Boolean Toggle){
Animation anim;
view.setVisibility(View.VISIBLE);
if(Toggle){
//fadeOut
anim = AnimationUtils.loadAnimation(regPP.this, R.anim.fadeout);
Log.d("FADE","FadeOut");
} else {
//fadeIn
anim = AnimationUtils.loadAnimation(regPP.this, R.anim.fadein);
Log.d("FADE","FadeIn");
}
view.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation arg0) {
//Functionality here
if(Toggle){
view.setVisibility(View.GONE);
Log.d("FADE", "FadeOut Callback");
} else {
view.setVisibility(View.VISIBLE);
Log.d("FADE", "FadeIn Callback");
}
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.lang = getResources().getString(R.string.lang);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final Context context = regPP.this;
setContentView(R.layout.reg_pp);
ImageButton uploadTog = (ImageButton) findViewById(R.id.uploadTog);
options = (LinearLayout) findViewById(R.id.uploadOptions);
uploadTog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fade(options,false);
optionsActive = true;
}
});
}
#Override
public void onBackPressed() {
if(optionsActive){
fade(options,true);
optionsActive = false;
} else {
super.onBackPressed();
}
}
}
remove this line may help u
android:visibility="gone"
visibility is gone that's why your view is not visible
android:visibility="gone"

Creating a progress bar for android

Hi I am new to threading in general and I am trying to set up a progress bar that increments itself every half-second up to 100 using the sleep method. I have been having trouble using a lot of the syntax I have found on line and when I launch this program it does not display a progress bar but instead displays a spinning loading icon. This is what I have:
public class main extends ActionBarActivity {
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(1);
startPb();
}
});
}
private void startPb(){
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setIndeterminate(false);
pb.setProgress(0);
new Thread(new Runnable(){
public void run(){
for (int i = 0; i <= 100; i++)
try {
Thread.sleep(500);
pb.setProgress(i);
System.out.println(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
pb.post(new Runnable() {
public void run() {
pb.incrementProgressBy(1);
}
});
}
}).start();
}
I have a feeling I am not implementing the progress bar properly in the above code.
Layout:
<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=".Counter"
android:id="#+id/counter"
tools:ignore="InvalidId">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="startButton"
android:id="#+id/startbutton"
android:layout_centerHorizontal="true" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#+id/startbutton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
A spinning progress bar is an indeterminate progress bar. To use an actual progress bar you will want to call:
pb.setIndeterminate(false);
The progress bar style was also an issue. Here is a good reference explaining progress bar style types.
What's the meaning of android:progressBarStyle attribute in ProgressBar?

Categories

Resources