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

如何以编程方式在Android FrameLayout中对齐ImageButton,android,android-imagebutton,android-framelayout,Android,Android Imagebutton,Android Framelayout,我的应用程序的布局是FrameLayout。我想将ImageButton与framelayout的右上方对齐。我试过下面的代码不工作 mImageButton = new ImageButton(mContext); LayoutParams ll = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ); ll.gravity = Gravity.RIGHT; mImageB

我的应用程序的布局是FrameLayout。我想将ImageButton与framelayout的右上方对齐。我试过下面的代码不工作

    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\u width
layout\u height
值设置为
MATCH\u PARENT
,这样您的ImageView将填充所有父框架布局。

我认为您应该将LayoutParams的构造代码更改为:

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

在代码中,您将
layout\u width
layout\u height
值设置为
MATCH\u PARENT
,这样您的ImageView将填充所有父框架布局。

我认为您需要在布局参数中提供高度-宽度。因为使用match_parent时,它将采用parent的宽度和高度,或者您可以使用WRAP_内容

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

我认为您需要在布局参数中提供高度和宽度。因为使用match_parent时,它将采用parent的宽度和高度,或者您可以使用WRAP_内容

 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);
试试这个

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

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

mImageButton.setLayoutParams(params);

检查此资源,并尝试使用relativelayout。framelayout对你来说是一个硬性要求吗?@Manoj Rey Pham的解决方案正在发挥作用。检查这个资源,它说尝试使用relativelayout。框架布局对你来说是一个硬要求吗?@Manoj Rey Pham的解决方案正在运行检查答案这是否是更好的解决方案@Krishnacheck答案这是否是更好的解决方案@KrishnaI忘记添加重力。TOP。主要问题是您使用的是MATCH_PARENT。现在检查,这也应该工作。你可以给你的图像按钮指定特定的宽度和高度,这就是为什么我提到了宽度和高度。我还说过,你可以使用包裹内容,我忘了添加Gravity.TOP。主要问题是您使用的是MATCH_PARENT。现在检查,这也应该工作。你可以给你的图像按钮指定特定的宽度和高度,这就是为什么我提到了宽度和高度。我还说过,您可以使用包装内容