0

I am trying to add 9 buttons programmatically to a FrameLayout but only the last one is shown.

The code below is for the first button and I am doing like that for all the other buttons, but with different coordinates.

I want to add each button with these exact coordinates.

Sorry for bad English ;)

    FrameLayout.LayoutParams rel_btn = new FrameLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    Button button1 = new Button(this);
    button1.setBackgroundResource(R.drawable.empty);
    rel_btn.width = screenWidth/4;
    rel_btn.height = screenWidth/4; 
    rel_btn.leftMargin = screenWidth/8;
    rel_btn.topMargin = screenHeight-1100;              
    button1.setLayoutParams(rel_btn);
    rl.addView(button1);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Can you give more details on what your app does and why you need to have exact pixel-based layout of buttons? – vmagro Aug 14 '14 at 21:33
  • I am beginner and for learning I am trying to make a tic tac toe .I want it to be good on different devices with different resolutions . – Abel Ghazinyan Aug 14 '14 at 21:37
  • I edited my answer with advice to use an xml based layout using `dp`'s instead of pixels if you want it to work well on different screen sizes. – vmagro Aug 14 '14 at 21:40

2 Answers2

1

A FrameLayout "is designed to block out an area on the screen to display a single item". The last child view is displayed on top of all the earlier views. If you want them all to display in a vertical list, a LinearLayout would be better suited to what you are trying to do.

Edit: If you want it to work reliably on different screen sizes and resolutions you shouldn't use pixels, you should define your layout in xml using dps instead of pixels. You could make your root layout a RelativeLayout and define relationships for each of the buttons such as android:toRightOf="<id of button>"

vmagro
  • 181
  • 7
  • I doubt that `stacking` is the issue here. OP said: `The code I show you is for the first button and I am doing like that for other button of course with different coordinates`. – Vikram Aug 14 '14 at 21:18
  • Stacking sounds exactly like the issue described by the OP "but only the last one is shown" – vmagro Aug 14 '14 at 21:19
  • Yes it does. Except that OP _also_ says that s/he is using different coordinates for every `Button`. – Vikram Aug 14 '14 at 21:26
1

I found this answer that might explain your problem: FrameLayout margin not working

FrameLayout may be ignoring the margins because you didn't specify a gravity. Try adding a gravity: rel_btn.gravity = Gravity.TOP;

Community
  • 1
  • 1
Coeffect
  • 8,772
  • 2
  • 27
  • 42