Search code examples
androidviewviewgroup

How to Add a Child View to the Center of a ViewGroup


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);

Solution

    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);