I am creating a ProgressBar to be placed in the vertical center of a LinearLayout (other layouts will not work; I need to use a LinearLayout). Here is some code:
LinearLayout linearLayout = new LinearLayout(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER);
//add progressbar
ProgressBar progressBar = new ProgressBar(context);
progressBar.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.addView(progressBar);
I have a ContainerView which will hold the LinearLayout created above. Something like this:
public class ContainerView extends ScrollView {
public ContainerView(Context context) {
super(context);
initView(context);
}
private void initView(Context context){
addView(linearLayout); //which is created in the snippet above
}
}
If I extend ContainerView with LinearLayout, everything works fine.
If I extend ContainerView with ScrollView, ProgressBar is centered horizontally but not vertically.
What's the reason behind this dual behavior? My goal is to show a ProgressBar during the download of some data; once data is downloaded, I need to show it in the LinearLayout.
(Note: The reason for using ScrollView is that downloaded data may be too large to fit a small screen. This may seem like a use-case for ListView, but there are some other reasons that prevent me from using ListView.)
I got it working after setting the following attribute to my parent ScrollView :
android:fillViewport="true"