0

My app's layout is FrameLayout. I want to align an ImageButton to right top of the framelayout. I tried below code not worked.

    mImageButton = new ImageButton(mContext);
    LayoutParams ll = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT );
    ll.gravity = Gravity.RIGHT;
    mImageButton.setLayoutParams(ll);
    mImageButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_moreoverflow_normal_holo_light));
    this.addView(mImageButton);

expected outputexpected output

Cœur
  • 37,241
  • 25
  • 195
  • 267
Riskhan
  • 4,434
  • 12
  • 50
  • 76
  • check this resource http://stackoverflow.com/questions/6060688/how-can-i-align-an-element-to-the-right-in-the-framelayout it says try to use relativelayout. is framelayout a hard requirement for you? – Manoj K Feb 04 '16 at 05:54
  • @Manoj Rey Pham's solution is working – Riskhan Feb 04 '16 at 06:02

3 Answers3

1

I think you should change the construction code of LayoutParams to:

LayoutParams ll = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.gravity = Gravity.TOP | Gravity.RIGHT;

In your code, you set the layout_width and layout_height value to MATCH_PARENT , so your ImageView will fill all your parent FrameLayout.

Rey Pham
  • 605
  • 3
  • 11
1

I think you need to provide height width in layout params. Because with match_parent it will take width and height of parent or you can use WRAP_CONTENT.

 mImageButton = new ImageButton(mContext);
LayoutParams ll = new LayoutParams(width,height);
ll.gravity = Gravity.RIGHT | Gravity.TOP;
mImageButton.setLayoutParams(ll);
mImageButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_moreoverflow_normal_holo_light));
this.addView(mImageButton);
  • I forgot to add Gravity.TOP. Main problem was that you were using MATCH_PARENT. Check now this should also work . You can give specific width and height to your image button as well that's why I mentiond width height. I have also metioned that you can use wrap content – Damanpreet Singh Feb 04 '16 at 06:31
1

Try this,

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

params.gravity = Gravity.TOP | Gravity.RIGHT;

mImageButton.setLayoutParams(params);
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142