Android ProgressBar setProgress() doesn't work as intended - android

I'm working on a progress bar that shows the rating of a game.
Here an example CorrectGameRatingProgressBar.
Here's the code
ProgressBar userRatingProgressBar = root.findViewById(R.id.users_rating);
userRatingProgressBar.setProgress(0);
...
// game ratings
if (game.getRatingCount() > 0) {
userRatingProgressBar.setProgress((int) game.getRating());
gameUsersRatingText.setText(String.valueOf((int) game.getRating()));
} else {
userRatingProgressBar.setProgress(0);
gameUsersRatingText.setText("N/A");
}
...
It works well except for a thing: sometimes seems that setProgress(0) doesn't update the progress bar when I switch from a game to another that doesn't have a rating as shown here IncorrectGameRatingProgressBar. I even tried to set the progress bar to 0 before the "null check" but this thing happens anyway.
I tried this on a Xiaomi Mi9T with MIUI 12.0.5 (Android 10 QKQ1.190825.002) and on the Pixel 2 emulated on Android Studio with Android 11
Is there a way to fix this problem? If you need more infos, don't bother asking!
Thank you for all
I leave you down here the layout layout.xml of the activity
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/user_rating_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/GameDetailTextColor"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/users_rating"
app:layout_constraintEnd_toEndOf="#+id/users_rating"
app:layout_constraintStart_toStartOf="#+id/users_rating"
app:layout_constraintTop_toTopOf="#+id/users_rating"
tools:text="60" />
<ProgressBar
android:id="#+id/users_rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:indeterminateOnly="false"
android:progressDrawable="#drawable/rating_circle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:progress="60" />
</androidx.constraintlayout.widget.ConstraintLayout>
and the drawable custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="ring"
android:thicknessRatio="16"
android:useLevel="false">
<solid android:color="?attr/SearchBarBackgroundColor" />
</shape>
</item>
<item>
<rotate
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="3.1"
android:shape="ring"
android:thicknessRatio="12"
android:useLevel="true">
<solid android:color="#color/orange_700" />
</shape>
</rotate>
</item>
</layer-list>
EDIT:
here's the code of the java fragment:
public class GameDetailFragment extends Fragment {
...
private long gameId = 0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_game_detail, container, false);
if (getArguments() != null) {
gameId = getArguments().getLong("GAME_ID");
}
GameDetailViewModelFactory viewModelFactory = ((MainActivity) requireActivity()).getAppContainer().gameDetailViewModelFactory;
mViewModel = new ViewModelProvider(this, viewModelFactory).get(GameDetailViewModel.class);
...
ProgressBar userRatingProgressBar = root.findViewById(R.id.users_rating);
userRatingProgressBar.setProgress(0);
if (gameId != 0) {
...
// game ratings
if (game.getRatingCount() > 0) {
userRatingProgressBar.setProgress((int) game.getRating());
gameUsersRatingText.setText(String.valueOf((int) game.getRating()));
} else {
userRatingProgressBar.setProgress(0);
gameUsersRatingText.setText("N/A");
}
...
return root;
}
}

I find a solution!
Apparently I didn't set up the progress bar into the layout.xml
So, if you add android:progress="1" in the xml, the progress bar is getting updated everytime.

Related

Android progressbar set different background drawable on progress 0 and progress 100

I am trying to implement a circular download progress bar which can show different drawable
when the progress is 0(download not started)
when the progress is > 0 && < 100 (download in progress)
when the progress is 100(download complete)
I was able to implement the showing of circular progress bar when the progress is > 0 && < 100
with the below code
circle.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="ring"
android:thicknessRatio="16"
android:useLevel="false">
<solid android:color="#DDD" />
</shape>
</item>
<item>
<rotate
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:shape="ring"
android:thicknessRatio="16"
android:useLevel="true">
<gradient
android:endColor="#color/colorPrimary"
android:startColor="#color/colorAccent"
android:type="sweep" />
</shape>
</rotate>
</item>
</layer-list>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<ProgressBar
android:id="#+id/progress_bar"
style="#style/CircularDeterminateProgressBar"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:progress="60" />
<TextView
android:id="#+id/text_view_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintBottom_toBottomOf="#+id/progress_bar"
app:layout_constraintEnd_toEndOf="#+id/progress_bar"
app:layout_constraintStart_toStartOf="#+id/progress_bar"
app:layout_constraintTop_toTopOf="#+id/progress_bar"
tools:text="60%" />
<Button
android:id="#+id/button_decr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- 10%"
app:layout_constraintStart_toStartOf="#+id/progress_bar"
app:layout_constraintTop_toBottomOf="#+id/progress_bar" />
<Button
android:id="#+id/button_incr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+ 10%"
app:layout_constraintEnd_toEndOf="#+id/progress_bar"
app:layout_constraintTop_toBottomOf="#+id/progress_bar" />
</androidx.constraintlayout.widget.ConstraintLayout>
and my activity as below
class MainActivity : AppCompatActivity() {
private var progr = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
updateProgressBar()
button_incr.setOnClickListener {
if (progr <= 90) {
progr += 10
updateProgressBar()
}
}
button_decr.setOnClickListener {
if (progr >= 10) {
progr -= 10
updateProgressBar()
}
}
}
private fun updateProgressBar() {
progress_bar.progress = progr
text_view_progress.text = "$progr%"
}
}
I am not sure how to set a different drawable(download icon) when the download progress is 0 (not started) and other different drawable(download complete icon) when the download progress is 100.
Any pointers or solution would be really helpful?
Solution 1 : Use a LevelListDrawable. You will be able to define the different drawables to be used for different levels.
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="0" android:drawable="#drawable/ic_wifi_signal_1" />
<item android:maxLevel="1" android:drawable="#drawable/ic_wifi_signal_2" />
<item android:maxLevel="2" android:drawable="#drawable/ic_wifi_signal_3" />
<item android:maxLevel="3" android:drawable="#drawable/ic_wifi_signal_4" />
</level-list>
Documentation :
https://developer.android.com/reference/android/graphics/drawable/LevelListDrawable
Solution 2 : Update the drawable dynamically using ProgressBar.setIndeterminateDrawable() whenever you update the progress bar level.
Documentation :
https://developer.android.com/reference/android/widget/ProgressBar#setIndeterminateDrawable(android.graphics.drawable.Drawable)

set background screen blurr when running progressbar in android

Any one know how to set background blurr when progressbar wheel is running in andorid. I want that screen looks like blurr when circular wheel progress bar is running and no interaction in background.
I am using this code as i required same as you, which is best fit to your requirement too.
You can write this code in your base activity class and use it as your requirement.
ViewGroup progressView;
protected boolean isProgressShowing = false;
public void showProgressingView() {
if (!isProgressShowing) {
isProgressShowing = true;
progressView = (ViewGroup) getLayoutInflater().inflate(R.layout.progressbar_layout, null);
View v = this.findViewById(android.R.id.content).getRootView();
ViewGroup viewGroup = (ViewGroup) v;
viewGroup.addView(progressView);
}
}
public void hideProgressingView() {
View v = this.findViewById(android.R.id.content).getRootView();
ViewGroup viewGroup = (ViewGroup) v;
viewGroup.removeView(progressView);
isProgressShowing = false;
}
here progressbar_layout.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#BA000000">
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
This is simple and neat way to do this.
You can customize your progressbar_layout in any way, any color, any style.
Get rid of default android progress bar
Put ProgressBar control to your layout xml
<ProgressBar
android:id="#+id/progressBarDialog"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"
android:indeterminateDrawable="#drawable/myDialog" >
</ProgressBar>
Assign Id into your activity
private ProgressBar bar;
bar = (ProgressBar) findViewById(R.id.progressBarDialog);
Make one xml file named myDialog.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="8"
android:useLevel="false">
<size
android:width="48dip"
android:height="48dip" />
<gradient
android:centerColor="#color/color_preloader_center"
android:centerY="0.50"
android:endColor="#color/color_preloader_end"
android:startColor="#color/color_preloader_start"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
put following code in colors.xml
<color name="color_preloader_start">#000000</color>
<color name="color_preloader_center">#000000</color>
<color name="color_preloader_end">#ff56a9c7</color>
use simple progress bar in your xml
use dependancy
compile 'jp.wasabeef:blurry:2.1.1' in build.gradle
give id (content) to your xml which you want to blur during progress bar
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
in java copy this blurall() function
private void blurall() {
if (blurred) {
Blurry.delete((ViewGroup) findViewById(R.id.content));
} else {
long startMs = System.currentTimeMillis();
Blurry.with(viewprofile.this)
.radius(25)
.sampling(2)
.async()
.animate(500)
.onto((ViewGroup) findViewById(R.id.content));
Log.d(getString(R.string.app_name),
"TIME " + String.valueOf(System.currentTimeMillis() - startMs) + "ms");
}
blurred = !blurred;
}
first time call blurall() function will blur all your screen and second time call blurall() function will remove blur.Call blurall() function before progress bar start like
blurall();
progressBar.setVisibility(View.VISIBLE);
after that call again blurall() function after
progressBar.setVisibility(View.Gone);
blurall();
I am working with this, and it works perfectly for me.
In XML
<View
android:id="#+id/bgBox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#drawable/rounded_trans_overlay"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="30dp"
android:elevation="10dp"
android:foregroundGravity="center"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
rounded_trans_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#AAb9ebed"/>
<stroke
android:width="0.5dp"
android:color="#66295A75" />
<corners android:radius="20dp" />
</shape>
in Java have this function
public void loading(boolean val, Activity activity, ProgressBar progressBar, View view) {
if (val) {
view.setElevation(8);
progressBar.setVisibility(View.VISIBLE);
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
} else {
view.setElevation(0);
progressBar.setVisibility(View.GONE);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
}
To activate Call
loading(true, requireActivity(), binding.loading, binding.bgBox);
To deactivate
loading(false, requireActivity(), binding.loading, binding.bgBox);
simply add this line in your java code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,WindowManager.LayoutParams.FLAG_
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

How to Create a circular progressbar in Android which rotates on it?

I am trying to create a rounded progressbar. This is what I want to achieve
There is a grey color background ring. On top of it, a blue color progressbar appears which moves in a circular path from 0 to 360 in 60 or whatever amount of seconds.
Here is my example code.
<ProgressBar
android:id="#+id/ProgressBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="?android:attr/progressBarStyleLarge"
android:indeterminateDrawable="#drawable/progressBarBG"
android:progress="50"
/>
To do this, in the drawable "progressBarBG", I am creating a layerlist and inside that layer list I am giving two items as shown.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#android:id/background">
<shape
android:shape="ring"
android:innerRadius="64dp"
android:thickness="8dp"
android:useLevel="false">
<solid android:color="#color/grey" />
</shape>
</item>
<item android:id="#android:id/progress">
<clip>
<shape
android:shape="ring"
android:innerRadius="64dp"
android:thickness="8dp"
android:useLevel="false">
<solid android:color="#color/blue" />
</shape>
</clip>
</item>
Now, the first grey ring is generated fine. The blue ring however starts from the left of the drawable and goes to the right just like how a linear progressbar works. This is how it shows at 50% progress with the red color arrow showing direction.
I want to move the blue progressbar in circular path as expected.
Here are my two solutions.
Short answer:
Instead of creating a layer-list, I separated it into two files. One for ProgressBar and one for its background.
This is the ProgressDrawable file (#drawable folder): circular_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
And this is for its background(#drawable folder): circle_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadiusRatio="2.5"
android:thickness="1dp"
android:useLevel="false">
<solid android:color="#CCC" />
</shape>
And at the end, inside the layout that you're working:
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="200dp"
android:layout_height="200dp"
android:indeterminate="false"
android:progressDrawable="#drawable/circular_progress_bar"
android:background="#drawable/circle_shape"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="65" />
Here's the result:
Long Answer:
Use a custom view which inherits the android.view.View
Here is the full project on github
With the Material Components Library you can use the CircularProgressIndicator:
Something like:
<com.google.android.material.progressindicator.CircularProgressIndicator
app:indicatorColor="#color/...."
app:trackColor="#color/...."
app:indicatorSize="64dp"/>
You can use these attributes:
indicatorSize: defines the radius of the circular progress indicator
trackColor: the color used for the progress track. If not defined, it will be set to the indicatorColor and apply the android:disabledAlpha from the theme.
indicatorColor: the single color used for the indicator in determinate/indeterminate mode. By default it uses theme primary color
Use progressIndicator.setProgressCompat((int) value, true); to update the value in the indicator.
Note: it requires at least the version 1.3.0-alpha04.
I have done with easy way:
Please check screen shot for the same.
CustomProgressBarActivity.java:
public class CustomProgressBarActivity extends AppCompatActivity {
private TextView txtProgress;
private ProgressBar progressBar;
private int pStatus = 0;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_progressbar);
txtProgress = (TextView) findViewById(R.id.txtProgress);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
new Thread(new Runnable() {
#Override
public void run() {
while (pStatus <= 100) {
handler.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(pStatus);
txtProgress.setText(pStatus + " %");
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
pStatus++;
}
}
}).start();
}
}
activity_custom_progressbar.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.skholingua.android.custom_progressbar_circular.MainActivity" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:max="100"
android:progress="0"
android:progressDrawable="#drawable/custom_progressbar_drawable"
android:secondaryProgress="0" />
<TextView
android:id="#+id/txtProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/progressBar"
android:layout_centerInParent="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</RelativeLayout>
custom_progressbar_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="-90"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="270" >
<shape
android:shape="ring"
android:useLevel="false" >
<gradient
android:centerY="0.5"
android:endColor="#FA5858"
android:startColor="#0099CC"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Hope this will help you.
I have written detailed example on circular progress bar in android here on my blog demonuts.com. You can also fond full source code and explanation there.
Here's how I made circular progressbar with percentage inside circle in pure code without any library.
first create a drawable file called circular.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#android:id/secondaryProgress">
<shape
android:innerRadiusRatio="6"
android:shape="ring"
android:thicknessRatio="20.0"
android:useLevel="true">
<gradient
android:centerColor="#999999"
android:endColor="#999999"
android:startColor="#999999"
android:type="sweep" />
</shape>
</item>
<item android:id="#android:id/progress">
<rotate
android:fromDegrees="270"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="270">
<shape
android:innerRadiusRatio="6"
android:shape="ring"
android:thicknessRatio="20.0"
android:useLevel="true">
<rotate
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />
<gradient
android:centerColor="#00FF00"
android:endColor="#00FF00"
android:startColor="#00FF00"
android:type="sweep" />
</shape>
</rotate>
</item>
</layer-list>
Now in your activity_main.xml add following:
<?xml version="1.0" encoding="utf-8"?>
<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/dialog"
tools:context="com.example.parsaniahardik.progressanimation.MainActivity">
<ProgressBar
android:id="#+id/circularProgressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="250dp"
android:layout_height="250dp"
android:indeterminate="false"
android:max="100"
android:progress="50"
android:layout_centerInParent="true"
android:progressDrawable="#drawable/circular"
android:secondaryProgress="100"
/>
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:background="#drawable/whitecircle"
android:layout_centerInParent="true"/>
<TextView
android:id="#+id/tv"
android:layout_width="250dp"
android:layout_height="250dp"
android:gravity="center"
android:text="25%"
android:layout_centerInParent="true"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp" />
</RelativeLayout>
In activity_main.xml I have used one circular image with white background to show white background around percentage. Here is the image:
You can change color of this image to set custom color around percentage text.
Now finally add following code to MainActivity.java :
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.DecelerateInterpolator;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int pStatus = 0;
private Handler handler = new Handler();
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.circular);
final ProgressBar mProgress = (ProgressBar) findViewById(R.id.circularProgressbar);
mProgress.setProgress(0); // Main Progress
mProgress.setSecondaryProgress(100); // Secondary Progress
mProgress.setMax(100); // Maximum Progress
mProgress.setProgressDrawable(drawable);
/* ObjectAnimator animation = ObjectAnimator.ofInt(mProgress, "progress", 0, 100);
animation.setDuration(50000);
animation.setInterpolator(new DecelerateInterpolator());
animation.start();*/
tv = (TextView) findViewById(R.id.tv);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (pStatus < 100) {
pStatus += 1;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mProgress.setProgress(pStatus);
tv.setText(pStatus + "%");
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(8); //thread will take approx 1.5 seconds to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
If you want to make horizontal progressbar, follow this link, it has many valuable examples with source code:
http://www.skholingua.com/android-basic/user-interface/form-widgets/progressbar
I realized a Open Source library on GitHub CircularProgressBar that does exactly what you want the simplest way possible:
USAGE
To make a circular ProgressBar add CircularProgressBar in your layout XML and add CircularProgressBar library in your projector or you can also grab it via Gradle:
compile 'com.mikhaellopez:circularprogressbar:1.0.0'
XML
<com.mikhaellopez.circularprogressbar.CircularProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:background_progressbar_color="#FFCDD2"
app:background_progressbar_width="5dp"
app:progressbar_color="#F44336"
app:progressbar_width="10dp" />
You must use the following properties in your XML to change your CircularProgressBar.
Properties:
app:progress (integer) >> default 0
app:progressbar_color (color) >> default BLACK
app:background_progressbar_color (color) >> default GRAY
app:progressbar_width (dimension) >> default 7dp
app:background_progressbar_width (dimension) >> default 3dp
JAVA
CircularProgressBar circularProgressBar = (CircularProgressBar)findViewById(R.id.yourCircularProgressbar);
circularProgressBar.setColor(ContextCompat.getColor(this, R.color.progressBarColor));
circularProgressBar.setBackgroundColor(ContextCompat.getColor(this, R.color.backgroundProgressBarColor));
circularProgressBar.setProgressBarWidth(getResources().getDimension(R.dimen.progressBarWidth));
circularProgressBar.setBackgroundProgressBarWidth(getResources().getDimension(R.dimen.backgroundProgressBarWidth));
int animationDuration = 2500; // 2500ms = 2,5s
circularProgressBar.setProgressWithAnimation(65, animationDuration); // Default duration = 1500ms
Fork or Download this library here >> https://github.com/lopspower/CircularProgressBar
Here is a simple customview for display circle progress. You can modify and optimize more to suitable for your project.
class CircleProgressBar #JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val backgroundWidth = 10f
private val progressWidth = 20f
private val backgroundPaint = Paint().apply {
color = Color.LTGRAY
style = Paint.Style.STROKE
strokeWidth = backgroundWidth
isAntiAlias = true
}
private val progressPaint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = progressWidth
isAntiAlias = true
}
var progress: Float = 0f
set(value) {
field = value
invalidate()
}
private val oval = RectF()
private var centerX: Float = 0f
private var centerY: Float = 0f
private var radius: Float = 0f
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
centerX = w.toFloat() / 2
centerY = h.toFloat() / 2
radius = w.toFloat() / 2 - progressWidth
oval.set(centerX - radius,
centerY - radius,
centerX + radius,
centerY + radius)
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(centerX, centerY, radius, backgroundPaint)
canvas?.drawArc(oval, 270f, 360f * progress, false, progressPaint)
}
}
Example using
xml
<com.example.androidcircleprogressbar.CircleProgressBar
android:id="#+id/circle_progress"
android:layout_width="200dp"
android:layout_height="200dp" />
kotlin
class MainActivity : AppCompatActivity() {
val TOTAL_TIME = 10 * 1000L
override fun onCreate(savedInstanceState: Bundle?) {
...
timeOutRemoveTimer.start()
}
private var timeOutRemoveTimer = object : CountDownTimer(TOTAL_TIME, 10) {
override fun onFinish() {
circle_progress.progress = 1f
}
override fun onTick(millisUntilFinished: Long) {
circle_progress.progress = (TOTAL_TIME - millisUntilFinished).toFloat() / TOTAL_TIME
}
}
}
Result
I'm new so I can't comment but thought to share the lazy fix. I use Pedram's original approach as well, and just ran into the same Lollipop issue. But alanv over in another post had a one line fix. Its some kind of bug or oversight in API21. Literally just add android:useLevel="true" to your circle progress xml. Pedram's new approach is still the proper fix, but I just thought I share the lazy fix as well.
<?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/progress_circular_id"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:progress="30"
android:progressDrawable="#drawable/circular_progress_bar"
android:background="#drawable/circle_shape"
style="?android:attr/progressBarStyleHorizontal"
android:max="100">
</ProgressBar>
<TextView
android:id="#+id/textview_progress_status_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50%"
android:layout_centerInParent="true"
android:textStyle="bold"
android:textColor="#color/blue"
android:textSize="35dp">
</TextView>
<Button
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="click me"
android:textColor="#color/white"
android:layout_below="#+id/progress_circular_id"
android:layout_centerHorizontal="true"
>
</Button>
</RelativeLayout>
Create a Drawable File with name circle_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadiusRatio="2.5"
android:thickness="25dp"
android:useLevel="false">
<solid android:color="#CCC" />
</shape>
Create a file with circular_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="25dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
In java File For example purpose used fragmet.
public class FragmentRegistration extends BaseFragmentHelper {
View registrationFragmentView;
ProgressBar progressBar;
Button button;
int count=0;
#Override
public void onAttachFragment(#NonNull Fragment childFragment) {
super.onAttachFragment(childFragment);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
registrationFragmentView = inflater.inflate(R.layout.new_device_registration, container, false);
progressBar=(ProgressBar)registrationFragmentView.findViewById(R.id.progress_circular_id);
button=(Button) registrationFragmentView.findViewById(R.id.check);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count=count+10;
progressBar.setProgress(count);
}
});
return registrationFragmentView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
}
try this method to create a bitmap and set it to image view.
private void circularImageBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
paint.setTextSize(140);
canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}
#Pedram, your old solution works actually fine in lollipop too (and better than new one since it's usable everywhere, including in remote views) just change your circular_progress_bar.xml code to this:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp"
android:useLevel="true"> <!-- Just add this line -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
https://github.com/passsy/android-HoloCircularProgressBar is one example of a library that does this. As Tenfour04 stated, it will have to be somewhat custom, in that this is not supported directly out of the box. If this library doesn't behave as you wish, you can fork it and modify the details to make it work to your liking. If you implement something that others can then reuse, you could even submit a pull request to get that merged back in!
Change
android:useLevel="false"
to
android:useLevel="true"
for second sahpe with id="#android:id/progress
hope it works
package com.example.ankitrajpoot.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.VISIBLE);
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="48dp"
style="?android:attr/progressBarStyleLarge"
android:layout_height="48dp"
android:indeterminateDrawable="#drawable/circular_progress_bar"
android:indeterminate="true" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:pivotX="50%"
android:pivotY="50%"
android:fromDegrees="0"
android:toDegrees="1080">
<shape
android:shape="ring"
android:innerRadiusRatio="3"
android:thicknessRatio="8"
android:useLevel="false">
<size
android:width="56dip"
android:height="56dip" />
<gradient
android:type="sweep"
android:useLevel="false"
android:startColor="#android:color/transparent"
android:endColor="#1e9dff"
android:angle="0"
/>
</shape>
</rotate>
Good news is that now material design library supports determinate circular progress bars too:
<com.google.android.material.progressindicator.CircularProgressIndicator
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
For more info about this refer here.
if you want to set progress in an anti-clock direction then use below image for set fromDegree and toDegree's values in progressDrawble xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="-90">
<shape
android:innerRadiusRatio="2"
android:shape="ring"
android:thickness="1dp">
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep" />
</shape>
</rotate>
This code will let your progress anti-clockwise and from the top.
Change the degrees as per the above image from where you want to rotate your progress bar.
You can use this library https://github.com/xYinKio/ArcCircleProgressBar
This is one of the most flexible circular progress bars
This picture is showing the lib powers

How to Customize a Progress Bar In Android

I am working on an app in which I want to show a ProgressBar, but I want to replace the default Android ProgressBar.
So how can I customize the ProgressBar?
Do I need some graphics and animation for that?
I read the following post but could not get it to work:
Custom Progress bar Android
Customizing a ProgressBar requires defining the attribute or properties for the background and progress of your progress bar.
Create an XML file named customprogressbar.xml in your res->drawable folder:
custom_progressbar.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Define the background properties like color etc -->
<item android:id="#android:id/background">
<shape>
<gradient
android:startColor="#000001"
android:centerColor="#0b131e"
android:centerY="1.0"
android:endColor="#0d1522"
android:angle="270"
/>
</shape>
</item>
<!-- Define the progress properties like start color, end color etc -->
<item android:id="#android:id/progress">
<clip>
<shape>
<gradient
android:startColor="#007A00"
android:centerColor="#007A00"
android:centerY="1.0"
android:endColor="#06101d"
android:angle="270"
/>
</shape>
</clip>
</item>
</layer-list>
Now you need to set the progressDrawable property in customprogressbar.xml (drawable)
You can do this in the XML file or in the Activity (at run time).
Do the following in your XML:
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:progressDrawable="#drawable/custom_progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
At run time do the following
// Get the Drawable custom_progressbar
Drawable draw=res.getDrawable(R.drawable.custom_progressbar);
// set the drawable as progress drawable
progressBar.setProgressDrawable(draw);
Edit: corrected xml layout
In case of complex ProgressBar like this,
use ClipDrawable.
NOTE : I've not used ProgressBar here in this example. I've achieved
this using ClipDrawable by clipping image with Animation.
A Drawable that clips another Drawable based on this Drawable's current level value. You can control how much the child Drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars, by increasing the drawable's level with setLevel().
NOTE : The drawable is clipped completely and not visible when the level is 0
and fully revealed when the level is 10,000.
I've used this two images to make this CustomProgressBar.
scall.png
ballon_progress.png
MainActivity.java
public class MainActivity extends ActionBarActivity {
private EditText etPercent;
private ClipDrawable mImageDrawable;
// a field in your class
private int mLevel = 0;
private int fromLevel = 0;
private int toLevel = 0;
public static final int MAX_LEVEL = 10000;
public static final int LEVEL_DIFF = 100;
public static final int DELAY = 30;
private Handler mUpHandler = new Handler();
private Runnable animateUpImage = new Runnable() {
#Override
public void run() {
doTheUpAnimation(fromLevel, toLevel);
}
};
private Handler mDownHandler = new Handler();
private Runnable animateDownImage = new Runnable() {
#Override
public void run() {
doTheDownAnimation(fromLevel, toLevel);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etPercent = (EditText) findViewById(R.id.etPercent);
ImageView img = (ImageView) findViewById(R.id.imageView1);
mImageDrawable = (ClipDrawable) img.getDrawable();
mImageDrawable.setLevel(0);
}
private void doTheUpAnimation(int fromLevel, int toLevel) {
mLevel += LEVEL_DIFF;
mImageDrawable.setLevel(mLevel);
if (mLevel <= toLevel) {
mUpHandler.postDelayed(animateUpImage, DELAY);
} else {
mUpHandler.removeCallbacks(animateUpImage);
MainActivity.this.fromLevel = toLevel;
}
}
private void doTheDownAnimation(int fromLevel, int toLevel) {
mLevel -= LEVEL_DIFF;
mImageDrawable.setLevel(mLevel);
if (mLevel >= toLevel) {
mDownHandler.postDelayed(animateDownImage, DELAY);
} else {
mDownHandler.removeCallbacks(animateDownImage);
MainActivity.this.fromLevel = toLevel;
}
}
public void onClickOk(View v) {
int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;
if (toLevel == temp_level || temp_level > MAX_LEVEL) {
return;
}
toLevel = (temp_level <= MAX_LEVEL) ? temp_level : toLevel;
if (toLevel > fromLevel) {
// cancel previous process first
mDownHandler.removeCallbacks(animateDownImage);
MainActivity.this.fromLevel = toLevel;
mUpHandler.post(animateUpImage);
} else {
// cancel previous process first
mUpHandler.removeCallbacks(animateUpImage);
MainActivity.this.fromLevel = toLevel;
mDownHandler.post(animateDownImage);
}
}
}
activity_main.xml
<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:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/etPercent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="number"
android:maxLength="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:onClick="onClickOk" />
</LinearLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/scall" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/clip_source" />
</FrameLayout>
clip_source.xml
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:clipOrientation="vertical"
android:drawable="#drawable/ballon_progress"
android:gravity="bottom" />
In case of complex HorizontalProgressBar just change cliporientation in clip_source.xml like this,
android:clipOrientation="horizontal"
You can download complete demo from here.
in your xml
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/CustomProgressBar"
android:layout_margin="5dip" />
And in res/values/styles.xml:
<resources>
<style name="CustomProgressBar" parent="android:Widget.ProgressBar.Horizontal">
<item name="android:indeterminateOnly">false</item>
<item name="android:progressDrawable">#drawable/custom_progress_bar_horizontal</item>
<item name="android:minHeight">10dip</item>
<item name="android:maxHeight">20dip</item>
</style>
<style name="AppTheme" parent="android:Theme.Light" />
</resources>
And custom_progress_bar_horizontal is a xml stored in drawable folder which defines your custom progress bar. For more detail see this blog.
I hope this will help you.
There are two types of progress bars called determinate progress bar (fixed duration) and indeterminate progress bar (unknown duration).
Drawables for both of types of progress bar can be customized by defining drawable as xml resource. You can find more information about progress bar styles and customization at http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples.
Customizing fixed or horizontal progress bar :
Below xml is a drawable resource for horizontal progress bar customization.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#android:id/background"
android:gravity="center_vertical|fill_horizontal">
<shape android:shape="rectangle"
android:tint="?attr/colorControlNormal">
<corners android:radius="8dp"/>
<size android:height="20dp" />
<solid android:color="#90caf9" />
</shape>
</item>
<item android:id="#android:id/progress"
android:gravity="center_vertical|fill_horizontal">
<scale android:scaleWidth="100%">
<shape android:shape="rectangle"
android:tint="?attr/colorControlActivated">
<corners android:radius="8dp"/>
<size android:height="20dp" />
<solid android:color="#b9f6ca" />
</shape>
</scale>
</item>
</layer-list>
Customizing indeterminate progress bar
Below xml is a drawable resource for circular progress bar customization.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#android:id/progress"
android:top="16dp"
android:bottom="16dp">
<rotate
android:fromDegrees="45"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="315">
<shape android:shape="rectangle">
<size
android:width="80dp"
android:height="80dp" />
<stroke
android:width="6dp"
android:color="#b71c1c" />
</shape>
</rotate>
</item>
</layer-list>
Customizing the color of progressbar namely in case of spinner type needs an xml file and initiating codes in their respective java files.
Create an xml file and name it as progressbar.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="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
tools:context=".Radio_Activity" >
<LinearLayout
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ProgressBar
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
</LinearLayout>
Use the following code to get the spinner in various expected color.Here we use the hexcode to display spinner in blue color.
Progressbar spinner = (ProgressBar) progrees.findViewById(R.id.spinner);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#80DAEB"),
android.graphics.PorterDuff.Mode.MULTIPLY);
For using custom drawable:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:drawable="#drawable/my_drawable"
android:pivotX="50%"
android:pivotY="50%" />
(add under res/drawable progress.xml). my_drawable may be xml, png
Then in your layout use
<ProgressBar
android:id="#+id/progressBar"
android:indeterminateDrawable="#drawable/progress_circle"
...
/>
Creating Custom ProgressBar like hotstar.
Add Progress bar on layout file and set the indeterminateDrawable with drawable file.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/player_progressbar"
android:indeterminateDrawable="#drawable/custom_progress_bar"
/>
Create new xml file in res\drawable
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Simplest way to create customize a progress bar in Android:
Initialize and show dialog:
MyProgressDialog progressdialog = new MyProgressDialog(getActivity());
progressdialog.show();
Create method:
public class MyProgressDialog extends AlertDialog {
public MyProgressDialog(Context context) {
super(context);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
#Override
public void show() {
super.show();
setContentView(R.layout.dialog_progress);
}
}
Create layout 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:background="#android:color/transparent"
android:clickable="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<ProgressBar
android:id="#+id/progressbarr"
android:layout_width="#dimen/eightfive"
android:layout_height="#dimen/eightfive"
android:layout_centerInParent="true"
android:indeterminateDrawable="#drawable/progresscustombg" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/progressbarr"
android:layout_marginTop="#dimen/_3sdp"
android:textColor="#color/white"
android:text="Please wait"/>
</RelativeLayout>
</RelativeLayout>
Create shape progresscustombg.xml and put res/drawable:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="20"
android:useLevel="false" >
<size
android:height="#dimen/eightfive"
android:width="#dimen/eightfive" />
<gradient
android:centerY="0.50"
android:endColor="#color/color_green_icash"
android:startColor="#FFFFFF"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
If you want to do this in code, here is a sample:
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
tv.setText("Waiting...");
pd.setCustomTitle(tv);
pd.setIndeterminate(true);
pd.show();
Using TextView gives you an option to change color, size, and font of your text. Otherwise you can just call setMessage(), as usual.
<ProgressBar
android:indeterminateDrawable="#drawable/loading"
style="?android:attr/progressBarStyleLarge"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleY="0.5"
android:scaleX="0.5"
android:id="#+id/progressBarGallery"/>
and #drawable/loading is src\main\res\drawable\loading.gif file, and its size is 200 by 200

Custom FragmentDialog with round corners and not 100% screen width

I am creating a custom fragment dialog with round corners and with layout that would not fill the screen width (I would prefer if it just wrapped its content).
this is my rounded_dialog.xml in drawable folder, which is called by my Custom ThemeWithCorners as a background for the dialog. I also tried to set it as background to the linear layout which creates its content but nothing works.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="#android:color/white"/>
<corners android:radius="20dp"
/>
</shape>
and this is how i call the dialog:
final String FTAG = "TAG_FRAGMENT_DIALOG_CALENDAR";
dialog = (CalendarDialog) fm.findFragmentByTag(FTAG);
ft = fm.beginTransaction();
if (dialog != null)
{
ft.remove(dialog);
}
dialog = CalendarDialog.newInstance(this);
dialog.setCancelable(true);
ft.add(dialog, FTAG);
ft.show(dialog);
ft.commit();
In onCreate method of the dialog I set the style and theme:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.ThemeWithCorners);
}
This is the onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setCanceledOnTouchOutside(true);
v = (MyCalendar)inflater.inflate(R.layout.calendar_dialog, container, true)
return v;
}
I also tried to add this to onCreateDialog method as other answers on SO suggested but did not work either:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog d = super.onCreateDialog(savedInstanceState);
LayoutParams lp=d.getWindow().getAttributes();
d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
lp.width=-2;lp.height=-2;lp.gravity=Gravity.CENTER;
lp.dimAmount=0;
lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;
return d;
}
So to sum it up, I want round corners, not 100% width of the screen, it preferably should wrap its content. Please, please, I need some help, I am really desperate about this, I´v ebeen trying it for days!
Dialog background: dialog_rounded_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/white" />
<corners android:radius="12dp" />
</shape>
Dialog layout: dialog_rounded.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/dialog_rounded_bg"
android:minWidth="260dp"
android:orientation="vertical"
android:padding="24dp">
...
</LinearLayout>
Dialog fragment: RoundedDialog.java
public class RoundedDialog extends DialogFragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_rounded, container, false);
// Set transparent background and no title
if (getDialog() != null && getDialog().getWindow() != null) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
return view;
}
...
}
Update: If you don't set the flag Window.FEATURE_NO_TITLE, a blue line appears on top of the dialog in devices with Android ≤ 4.4.
Well, I just found a solution, I am not really happy with it though.
I set the background (rounded_dialog.xml) for the dialog like this:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/transparent"/>
<corners android:radius="10dp" />
<padding android:left="10dp" android:right="10dp"/>
</shape>
Then I set this to my dialog in its ´onCreateView´ method this way below. The rounded corners are not really necessary in this piece of code as the background is transparent, but the padding is important, because the dialog is still in fact as wide as the screen, but the padding makes it look like it is not.
getDialog().getWindow().setBackgroundDrawableResource(R.drawable.rounded_dialog);
And in the end I set background of the dialog´s components to another custom drawable which makes the corners round. I have a LinearLayout with RelativeLayout at the top and TextView at the bottom, so I set #null to the parent LinearLayout and set two different custom drawables to the two parts, one of which has rounded bottomCorners and the other one topCorners.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/title_round"
>
<RelativeLayout
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/blue_title_round_top"
android:paddingTop="4dp"
android:paddingBottom="4dp"
>
<TextView
android:id="#+id/calendarHint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rounded_bottom"
android:layout_gravity="center"
android:gravity="center"
/>
</LinearLayout>
I believe there is a more proper solution to this as this is correct just visually, not really functionally, but enough correct for this case.
Updated 2022 answer with Kotlin and View Binding -
class InternetLostDialog : DialogFragment() {
private lateinit var binding: DialogInternetLostBinding
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DialogInternetLostBinding.inflate(LayoutInflater.from(context))
val builder = AlertDialog.Builder(requireActivity())
isCancelable = false
builder.setView(binding.root)
binding.root.setOnClickListener {
requireActivity().finish()
}
val dialog = builder.create()
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return dialog
}
}
Another way:
Use setStyle() in onCreate() method to apply a style to your DialogFragment.Then, you can use android:background same as always in the root view of your_layout.xml file.
Steps:
style.xml file (in res folder) :
<style name="DialogTheme_transparent" parent="Theme.AppCompat.Dialog">
<item name="android:windowBackground">#android:color/transparent</item>
<!--You can set other style items also, such as animations and etc-->
</style>
Create your_layout.xml file in the layout folder:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:background="#drawable/bg_corner_dialog">
...
</LinearLayout>
Create bg_corner_dialog.xml file in the drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:dither="true">
<solid android:color="#ffffff"/>
<corners android:radius="16dp"/>
</shape>
Finally apply style and layout to the your DialogFragment:
public class CustomDialogFragment extends DialogFragment {
...
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, R.style.DialogTheme_transparent);
...
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_layout, container, false);
ButterKnife.bind(this, v);
//init UI Elements...
return v;
}
}
I hope this helps you.
Best wishes
An updated solution that works for me using Kotlin.
I set the background (rounded_dialog.xml) for the dialog like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="28dp" />
<solid android:color="#color/white"/>
</shape>
then calculating the screen width programmatically then subtract the Margin value from it, using this code snippet.
val displayMetrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
then inside onStart callback I applied that width minus Margin.
here is the full code.
#AndroidEntryPoint
class CancelDialogFragment : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
if (dialog != null && dialog?.window != null) {
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE);
}
return inflater.inflate(R.layout.fragment_cancel_dialog, container, false)
}
override fun onStart() {
super.onStart()
val displayMetrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics)
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
dialog?.window?.setLayout(width-64, ViewGroup.LayoutParams.WRAP_CONTENT)
}
}
XML Layout fragment_cancel_dialog
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:paddingVertical="32dp"
android:padding="8dp"
android:layout_marginHorizontal="8dp"
android:background="#drawable/rounded_dialog"
tools:context=".ui.orders.CancelDialogFragment">
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Reason of cancellation"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="#+id/firstNameTIL"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/firstNameTIL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="24dp"
android:layout_marginTop="16dp"
app:hintAnimationEnabled="false"
app:hintEnabled="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView9">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/firstNameET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/edit_text_bg"
android:drawablePadding="12dp"
android:inputType="textPersonName"
android:paddingHorizontal="16dp"
android:paddingVertical="16dp"
android:textAlignment="viewStart"
android:textColor="#color/textColor"
android:textColorHint="#color/black" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/signUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:layout_marginBottom="32dp"
android:background="#drawable/button_bg"
android:paddingHorizontal="56dp"
android:text="#string/confirmStr"
android:textAllCaps="false"
android:inputType="text"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstNameTIL" />
</androidx.constraintlayout.widget.ConstraintLayout>
There is a quick fix for DialogFragment. For example, in the method onCreateDialog() add style in AlertDialog.Builder(context, style):
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_dialog_lauout, null);
return new AlertDialog.Builder(getActivity(), R.style.custom_alert_dialog)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// do something
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}
In styles folder custom_alert_dialog
<style name="custom_alert_dialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">#drawable/corner_background</item>
</style>
In drawable folder corner_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="8dp" />
It's tested for API >= 21
For Any One who wants to Use the AlertDialogBuilder and transparent the background and set the Drawable in XML file.
<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<item name="android:background">#drawable/dialog_background</item>
<item name="android:windowBackground">#android:color/transparent</item>
Set this Theme on Builder like below
private val builder: AlertDialog.Builder = AlertDialog.Builder(context,R.style.DialogStyle)
.setView(dialogView)
where is R.drawable.dialog_background
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<solid
android:color="#color/dialog_bg_color"/>
<corners
android:radius="30dp" />
</shape>
</item>
I think to make rounded corners, its much easier if u make cardview as the root of your layout and add below code in onCreateView():
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transpare‌​nt)
This is an old question and it misses the simplest way of achieving rounded edges in a DialogFragment component. You can achieve this with one liner:
override fun getTheme() = R.style.RoundedCornersDialog

Categories

Resources