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

以编程方式将子视图添加到Android中的自定义视图,android,layout,webview,imagebutton,custom-view,Android,Layout,Webview,Imagebutton,Custom View,我试图做的只是在右上角添加一个imageButton视图作为自定义视图的子视图。我的自定义视图扩展了Webview。将imageButton添加到自定义视图没有问题,只是无法将其移动到右上角。我需要以编程的方式来做这件事,而不是用xml。我从没想过这么简单的事情需要我在这里发布,但我真的搞不懂 以下是我当前用于将imageButton添加到自定义视图的内容,但它位于左上角: public class customView extends WebView { private

我试图做的只是在右上角添加一个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解决方案。谢谢大家。

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

    customView.this.addView(child, params);

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

谢谢您的回答。我实际上想写closeImageButton.setLayoutParams(lp);那是个打字错误。很抱歉。虽然您建议的方法看起来应该可以使用,但按钮仍保留在左上角。可能您的自定义视图中还有其他设置未正确处理。是什么阻止您创建自定义RelativeLayout,将其称为customView,并同时包含自定义web视图和左上角带有设置的按钮?它仍将包含在一个有意义的“视图”中。我会试试的。明天我会告诉你的。