I want to draw a button in an android application at a specific point say (x,y), the point will be generated at runtime. So how can I achieve it.
Asked
Active
Viewed 2,250 times
4 Answers
0
For that use below code...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="50dip"
android:layout_height="50dip"
android:id="@+id/button"/>
</RelativeLayout>
in this code just Add android:layout_margin
by using margin u can set your button as per your requirement.....

Mitesh Jain
- 673
- 1
- 7
- 20
0
For that you can use AbsoluteLayout
which can help you in setting the exact position of the view by the property of the view android:layout_x
and android:layout_y
UPDATE
To add x, y on Runtime check these,

Community
- 1
- 1

Lalit Poptani
- 67,150
- 23
- 161
- 242
-
1FYI, AbsoluteLayout is deprecated. – Paresh Mayani Oct 24 '11 at 06:59
-
So, let me know what is the harm in using a deprecated layout. – Lalit Poptani Oct 24 '11 at 07:03
0
If you are using a LinearLayout:
Button button = (Button)findViewById(R.id.my_button);
LinearLayout.LayoutParams linParams =
(LinearLayout.LayoutParams)button.getLayoutParams();
linParams.setMargins(left, top, right, bottom);
button.setLayoutParams(linParams);

Reno
- 33,594
- 11
- 89
- 102
0
Create a RelativeLayout layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/mybutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
Then in your code:
int posX = 10, posY = 20;
Button b = findViewById(R.id.mybutton);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(posX, posY, 0, 0);
b.setLayoutParams(layoutParams);

ImR
- 787
- 6
- 8
-
You are using a RelativeLayout in xml and treating it as a LinearLayout in code, will that work? – Reno Oct 24 '11 at 06:41