Set attributes (margin, gravity, etc.) On an Android view programmatically (without XML)

I need to create a GUI (layout + views) in my .java activity class (I know this is a much more flexible and easy to use .xml layout file, but I don't want to use it yet).

I cannot find setGravity () (but the "Gravity" object, which I cannot figure out how to use) or any setMargin () method for the "View" object.

What is the easiest way to do this?

Thanx.

+5
android user-interface
source share
2 answers

Specifies a field for the component. The following leaves the existing fields as previously set and sets the left field to zero.

TextView title = ((TextView)findViewById(R.id.default_panel_title)) final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)title.getLayoutParams(); lpt.setMargins(0,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin); title.setLayoutParams(lpt); 
+7
source share

You can add gravity to "layouts" rather than to "controls." Try setting gravity for any of your linear / relative or frame layouts with setGravity () ;.

For example:

 LinearLayout lll = (LinearLayout) findViewById(R.id.layoutname); lll.setGravity(Gravity.CENTER); 
+1
source share

All Articles