如何以编程方式对齐 Android FrameLayout 中的 ImageButton

How to align an ImageButton in Android FrameLayout programmatically

我的应用程序的布局是 FrameLayout。我想将 ImageButton 对齐到框架布局的右上方。我试过下面的代码没有用。

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

预期输出

我觉得你应该把LayoutParams的构造代码改成:

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

在您的代码中,您将 layout_widthlayout_height 值设置为 MATCH_PARENT ,因此您的 ImageView 将填充所有父 FrameLayout。

我认为您需要在布局参数中提供高度宽度。因为使用 match_parent 它将占用父级的宽度和高度,或者您可以使用 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);

试试这个,

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

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

mImageButton.setLayoutParams(params);