Android examples for User Interface:Layout
Set layout_gravity="center" for the view.
//package com.java2s; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class Main { /**//from www . j a va2s . com * Set layout_gravity="center" for the view. * Note that this view's LayoutParams should be one of FrameLayout.LayoutParams * or LinearLayout.LayoutParams or RelativeLayout.LayoutParams. * * @param view */ public static void setViewCenterInParent(View view) { ViewGroup.LayoutParams lp = view.getLayoutParams(); // set layout_gravity if (lp instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) lp).gravity = android.view.Gravity.CENTER; } else if (lp instanceof LinearLayout.LayoutParams) { ((LinearLayout.LayoutParams) lp).gravity = android.view.Gravity.CENTER; } else if (lp instanceof RelativeLayout.LayoutParams) { ((RelativeLayout.LayoutParams) lp) .addRule(RelativeLayout.CENTER_IN_PARENT); } } }