Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the width of a ProgressBar added at runtime

I am building up a UI from code and can successfully add ProgressBar widgets, however I cannot alter the dimensions of the widget to values I need, it always stays at the default size (around 50dp). I've tried the following code;

    ProgressBar progressBar = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal);
    progressBar.setMinimumHeight(20);
    progressBar.setMinimumWidth(100);

I've also tried setting the progressBar LayoutParams but again nothing and I've tried wrapping the widget in another layout, but still not luck.

Can anyone help, as I can't see how to do it? If there is a solution using XML it could work, but I have to set the dimension and location at runtime.


For Progress XML I used the following.

<ProgressBar
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="fill_parent"
      android:layout_height="10dp"
      android:indeterminateOnly="false"
      android:progressDrawable="@android:drawable/progress_horizontal"
      android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
      android:maxWidth="1000dp"
   />

Then the code to inflate it is as follows. This is a mix of what we have been discussing.

    LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ProgressBar progressBar = (ProgressBar)layoutInflater.inflate(R.layout.progress_bar, null);
    progressBar.setMinimumHeight(10);
    progressBar.setMinimumWidth(200);
    progressBar.setLayoutParams(new RelativeLayout.LayoutParams(200, 10);

    progressBar.setMax(100);
    progressBar.setProgress(getScrollBarValue());
    progressBar.setIndeterminate(isIndeterminate());
    progressBar.getLayoutParams().width = 200;
    progressBar.invalidate();
like image 248
Snowwire Avatar asked Feb 15 '11 18:02

Snowwire


1 Answers

R.layout.activity includes this:

<ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        android:visibility="visible"
        style="@android:style/Widget.ProgressBar.Large.Inverse"
/>

And then the code:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
    ProgressBar bar = (ProgressBar)findViewById(R.id.progress);
    bar.getLayoutParams().height = 500;
    bar.invalidate();
}

The call to the invalidate() method is important as that is when the view is redrawn to take the changes into account. Although unintuitive, it does allow for better performance by batching changes.

like image 97
Ollie C Avatar answered Oct 19 '22 01:10

Ollie C