如何在视图上添加视图(例如图像上的按钮)

时间:2015-11-19 12:20:01

标签: android button imageview

图像在imageview中设置。我借助以下代码在图像上成功绘制文本。

private int instance;

但我想在不同高度和宽度的图像上绘制按钮。

1 个答案:

答案 0 :(得分:1)

    If you already define your imageView inside relative layout in xml than just instantiate it by findViewById

             //RelativeLayout relativeLayout =(RelativeLayout)(findViewById(.....));

    otherwise dynamically create relative layout like this

    RelativeLayout relativeLayout = new RelativeLayout(this);        
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT,
                            RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_IN_PARENT);
    relativeLayout.setLayoutParams(lp);
    relativeLayout.addView(imageview);

    //than create button dynmaically
                    Button b = new Button(this);
                    b.setText("Button");
                    RelativeLayout.LayoutParams btnrl = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT,
                            RelativeLayout.LayoutParams.WRAP_CONTENT);
                    btnrl.addRule(RelativeLayout.ALIGN_BOTTOM);
                    b.setLayoutParams(btnrl);

                    relativeLayout.addView(b);


        **Edit:**
In case you want arbitrary width and height than set button with and height like this


        int width = 0; // assign your width
        int height = 0; // assign your height
        RelativeLayout.LayoutParams btnrl = new RelativeLayout.LayoutParams(
                        width,height);
        btnrl.addRule(RelativeLayout.ALIGN_BOTTOM);
        b.setLayoutParams(btnrl);
相关问题