Question

What I am trying to do is simply add an imageButton view as a child of a custom view, in the top right corner. My custom view extends Webview. I have had no problem adding the imageButton to my custom view, I just can't move it to the top right corner. I need to do this programmatically, not in xml. I would never think something this simple would require me to post on here, but I really can't figure it out.

Here is what I am using to add the imageButton to the custom view currently, but it's at the top left corner:

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

What I have tried in order to move it to the top right corner:

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

As well as:

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

All of which results in the imageButton being placed in the top left corner. This is my first post on this site so I hope the question is properly formatted. Please no xml solutions. Thanks everyone.

Was it helpful?

Solution

I think what you are doing in your other two methods is literally setting your CustomView to have those layout params. What you should try instead is set the layout params of your child using this method;

    customView.this.addView(child, params);

where child is your image button and params is the layout params.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top