2

I have created a custom circular ProgressBar following this. Now I want to add this progress bar to the center of my layout. The problem is that it is added to the top left of the activity, no matter how I change LayoutParams attributes passed to addView(). The code is as follows:

// Create a progress bar to display while the list loads
            mProgressBar = new DualProgressView(getApplicationContext());

            ViewGroup root = findViewById(android.R.id.content);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(500, 500, Gravity.CENTER);
            root.addView(mProgressBar,params);
Mehdi Haghgoo
  • 3,144
  • 7
  • 46
  • 91
  • 1
    Just use it in xml with center align. or if you want to add it at runtime Then just assign LayoutParams as per parent layout. – ADM Dec 13 '17 at 10:16
  • 1
    The `android.R.id.content` `ViewGroup` is normally a `FrameLayout`, not a `LinearLayout`. You shouldn't really rely on that, though. Add your `DualProgressView` to a `ViewGroup` you've declared in your layout, so you know exactly what it is, and which `LayoutParams` to use. Btw, you should use the `Activity` for the `Context` you're instantiating that `DualProgressView` with, instead of `getApplicationContext()`, so it gets the right theme and styles applied. – Mike M. Dec 13 '17 at 10:21
  • @ADM Now I used `LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(root.getLayoutParams());` and it spans the whole width and does not align to the center vertically. I don't like it. – Mehdi Haghgoo Dec 13 '17 at 10:29
  • Agree with you Mike. @JasonStack I think the problem is in your DualProgressView . Post your DualProgressView.java – ADM Dec 13 '17 at 10:34
  • [DualProgressView.java](https://github.com/pollux-/DualProgressBar/blob/master/app/src/main/java/com/custom/progress/DualProgressView.java) – Mehdi Haghgoo Dec 13 '17 at 10:39
  • `ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(root.getLayoutParams()); root.addView(progressBar, params);` Also does NOT work! – Mehdi Haghgoo Dec 13 '17 at 10:44

1 Answers1

1
  1. make your progress bar height and width as wrap_content, or, say 40sp in xml.
  2. set attribute android:layout_gravity="center" to your ProgressBar within your LinearLayout.

or programmatically, try this:

ViewGroup layout = (ViewGroup) findViewById(android.R.id.content).getRootView();
LinearLayout.LayoutParams params = new 
        LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);

LinearLayout ll = new LinearLayout(thisActivity);

ll.setGravity(Gravity.CENTER);
ll.addView(progressBar);

layout.addView(ll,params);
Robillo
  • 192
  • 11