Search code examples
androidandroid-imagebuttonandroid-framelayout

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


Solution

  • 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.