以编程方式将子视图添加到Android中的自定义视图

时间:2012-11-22 00:07:16

标签: android layout webview imagebutton custom-view

我要做的只是在右上角添加一个imageButton视图作为自定义视图的子视图。我的自定义视图扩展了Webview。我将imageButton添加到我的自定义视图没有问题,我只是无法将其移动到右上角。我需要以编程方式执行此操作,而不是在xml中。我永远不会想到这么简单需要我在这里发帖,但我真的无法弄明白。

以下是我目前用于将imageButton添加到自定义视图的内容,但它位于左上角:

    public class customView extends WebView {

      private void imageButtonInit() {
         ImageButton closeImageButton = new ImageButton(getContext());
         Drawable image = getResources().getDrawable(com.package.image);
         closeImageButton.setBackgroundDrawable(image);
         closeImageButton.setLayoutParams(new RelativeLayout.LayoutParams(25, 25));
         closeImageButton.bringToFront();
         customView.this.addView(closeImageButton);
      }
    }

我试图将其移到右上角:

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(25, 25);
    lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, -1);
    closeImageButton.setLayoutParams(lp);
    customView.this.addView(closeImageButton);

以及:

    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(25, 25, Gravity.RIGHT|Gravity.TOP);
    closeImageButton.setLayoutParams(lp);
    customView.this.addView(closeImageButton);

所有这些都导致imageButton被放置在左上角。这是我在这个网站上的第一篇文章,所以我希望问题的格式正确。请不要xml解决方案。谢谢大家。

1 个答案:

答案 0 :(得分:1)

我认为你在其他两种方法中所做的是将 CustomView 设置为具有那些布局参数。您应该尝试使用此方法设置孩子的布局参数;

    customView.this.addView(child, params);

其中child是你的图像按钮,params是布局参数。

相关问题