Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to create a GUI (layout+views) in my .java activity class (I know it's far more flexible and easier to use .xml layout file, but I don't want to use it for now).

I can't find any setGravity() (but a "Gravity" object I can't figure how to use) or any set setMargin() method for the "View" object.

What is the easiest way to do it ?

Thanx.

like image 938
lethargicpanda Avatar asked Apr 27 '10 07:04

lethargicpanda


People also ask

How do I set margins programmatically in Android?

You should use LayoutParams to set your button margins: LayoutParams params = new LayoutParams( LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ); params.


2 Answers

For setting the margin on component. The following leaves the existing margins as previously set and sets the left margin as 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);
like image 79
Emile Avatar answered Nov 06 '22 00:11

Emile


You can add gravity to the "layouts" not to the "controls". Try to set gravity to any of your Linear/Relative or Frame layouts using setGravity(); .

Eg:

LinearLayout lll = (LinearLayout) findViewById(R.id.layoutname);
        lll.setGravity(Gravity.CENTER);
like image 23
Vishwanath Avatar answered Nov 06 '22 00:11

Vishwanath