Riskhan
Riskhan

Reputation: 4470

How to align an ImageButton in Android FrameLayout programmatically

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

Upvotes: 0

Views: 826

Answers (3)

Damanpreet Singh
Damanpreet Singh

Reputation: 726

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);

Upvotes: 1

Amit Vaghela
Amit Vaghela

Reputation: 22945

Try this,

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

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

mImageButton.setLayoutParams(params);

Upvotes: 1

Rey Pham
Rey Pham

Reputation: 605

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.

Upvotes: 1

Related Questions