Centering ProgressBar Programmatically in Android

android, android-progressbar

Solution

If you want to do it programatically you can do it like below:

RelativeLayout layout = new RelativeLayout(this);
progressBar = new ProgressBar(SignInActivity.this,null,android.R.attr.progressBarStyleLarge);
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100,100);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(progressBar,params);

setContentView(layout);

Problem

I'm trying to center a `ProgressBar` programmatically using the following: ``` ViewGroup layout = (ViewGroup) findViewById(android.R.id.content).getRootView(); progressBar = newProgressBar(SignInActivity.this,null,android.R.attr.progressBarStyleLarge); progressBar.setIndeterminate(true); progressBar.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100,100); params.addRule(RelativeLayout.CENTER_IN_PARENT); layout.addView(progressBar,params); ``` The size setting seems to work okay, but the `ProgressBar` doesn't center in the existing layout (defined by xml with a relative layout). Is there something obviously wrong here? The XML is as follows: ``` <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" tools:context=".test" android:typeface="monospace"> </RelativeLayout> ``` i.e. it's just an empty relative layout to test with and see if I can get it to programmatically add a progress bar. Thanks.

Original source