views:

73

answers:

2

Hello,

I have a button in my application.... I want to change its position by programmatically...

I have created a button in xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


<Button android:text="@+id/Button01" 
        android:id="@+id/Button01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_marginLeft="50px"
        android:layout_marginTop="10px"
        >
</Button>
</LinearLayout>

suppose if i wants to set the position of button as 100px from Left (as layout_marginLeft="100px") then how do i do it programatically?

pls help me and take me out from this problem. Thanx - Paresh

+2  A: 

You need to get the view and transform into a Java object, then call setPadding on it.

some thing like this would work out

Button myBtn;
myBtn=(Button)findViewById(R.id.Button01);
myBtn.setPadding(0,100,0,0);

Read more here: http://developer.android.com/intl/de/reference/android/view/ViewGroup.MarginLayoutParams.html

Pentium10
its not working ..showing red line (error) under setMargins function.I am using Android 1.5
PM - Paresh Mayani
Try setPadding.
Pentium10
i have also tried btnTest.setPadding(100,0,0,0); but it makes button of 100 width and text will be displyed on Right-hand side.but still not working
PM - Paresh Mayani
yeh...this working if i set "setPadding(100,0,0,0) to the Layout as follows: LinearLayout l1 = (LinearLayout) findViewById(R.id.LinearLayout01); l1.setPadding(120, 0, 0, 0);Thanx a lot...@Pentium
PM - Paresh Mayani
+2  A: 

Padding and margin are not the same ... this is thread is what you are looking for http://stackoverflow.com/questions/2481455/set-margins-in-a-linearlayout-programmatically

Mojo Risin
this link is helpful for me...but My Layout contains 9 buttons...so some are visible and invisible based on the condition..so i want to align(move left or right) it programmatically...pls help me
PM - Paresh Mayani
Have you notice that except visible, invisible there is also hide option for view visibility http://developer.android.com/reference/android/view/View.html#GONE. It depends on what are planning to do but one clean solution will be just to align your buttons in xml and when you don't need them to set visibility to gone. If this doesn't help please provide more info so we can help you.
Mojo Risin