How to create a ProgressBar programmatically?

AndroidAndroid Progressbar

Android Problem Overview


My application needs to create a small ProgressBar programmatically. ProgressBar doesn't have a method to set the style (I want a small ProgressBar). The constructor can take an AttributeSet, however, it is an interface and requires me to implement a set of functions. Is there a way to set the ProgressBar to a small style? (I can't use XML to create ProgressBar.)

Android Solutions


Solution 1 - Android

Most of the time if you provide an AttributeSet manually you have to use one of Android's. Luckily, they've exposed the attribute set that describes a small progress bar. Use this code:

progressBar = new ProgressBar(activity, null, android.R.attr.progressBarStyleSmall);

Solution 2 - Android

Create a layout xml file in res/layout directory with desired progress bar containig all attributes you need:

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" ... />

Next in the Activity class you can create ProgressBar object from that layout:

LayoutInflater inflater = getLayoutInflater();
	ProgressBar bar = (ProgressBar ) inflater.inflate(R.layout.small_progress_bar, null);

where R.layout.small_progress_bar links to your layout xml file.

Can you still not use xml file?

Solution 3 - Android

Activity.java

  progressBar = (ProgressBar) findViewById(R.id.progressbar);
 `progressBar.setVisibility(View.VISIBLE);`// To Show ProgressBar 
 `progressBar.setVisibility(View.INVISIBLE);` //To Hide ProgressBar

Check here https://stackoverflow.com/questions/45373007/progressdialog-is-deprecated-what-is-the-alternate-one-to-use/45613741#45613741

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAruthaView Question on Stackoverflow
Solution 1 - AndroidNeil TraftView Answer on Stackoverflow
Solution 2 - AndroidplugmindView Answer on Stackoverflow
Solution 3 - AndroidGowthaman MView Answer on Stackoverflow