1

Most of the pages in my application have a progress bar implementation. I would like to create a custom view group which always includes a progress bar.

For example,

<LinearLayout ...>
<ProgressBar .../>
</LinearLayout>

Can I create something like

<ActivityBody...>
//Other elements
</ActivityBody>

Where activity body always has the ProgressBar so I can always just hide and show progress bar as needed without including the progress bar each time.

4
  • sure, provided ActivityBody is a ViewGroup (custom LinearLayout for example)
    – pskink
    Commented Nov 15, 2016 at 16:00
  • yes, but an example to illustrate how i would add the progress bar to the ActivityBody will be great.
    – F.O.O
    Commented Nov 15, 2016 at 16:41
  • just call addView()
    – pskink
    Commented Nov 15, 2016 at 17:03
  • developer.android.com/training/improving-layouts/…
    – petey
    Commented Nov 15, 2016 at 18:10

1 Answer 1

1

create new custom ViewGroup extends FrameLayout

like this :

public class CustomLayout extends FrameLayout {
    ProgressBar myProgressBar;
    public CustomLayout (Context context) {
        super(context);
    }

    public CustomLayout (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomLayout (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void show() {
        if (myProgressBar == null) {
            addMyProgressBar();
        }
        myProgressBar.setVisibility(VISIBLE);
    }

    public void hide() {
        if (myProgressBar == null) {
            addMyProgressBar();
        }
        myProgressBar.setVisibility(GONE);
    }

    private void addMyProgressBar() {
        myProgressBar = new ProgressBar(getContext());
        LayoutParams params = new LayoutParams(100, 100, Gravity.CENTER);
        addView(myProgressBar, params);
    }
}

if you want to make ProgressBar always on Top:

  • edit show(), and hide() methods.
  • add removeMyProgressBar() method.

to be like this :

public void show() {
    if (myProgressBar == null)
        addMyProgressBar();
}

public void hide() {
    if (myProgressBar != null)
        removeMyProgressBar();
}

private void removeMyProgressBar() {
    if (myProgressBar != null) {
        removeView(myProgressBar);
        myProgressBar = null;
    }
}
1
  • This should be marked as the accepted answer. I followed the steps here and modified them for my own purposes and it was the perfect guide to solving my problem. Commented Apr 18, 2018 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.