如何以编程方式在图像上叠加文本

时间:2012-12-05 14:41:19

标签: android

我在相对布局中放置了一个图像。如何在背景图像上放置一个小图像,并在图像旁边并排放置两个文本视图。任何帮助将非常感激。唯一的问题是我想以编程方式执行此操作。我尝试过以下方式,但由于某种原因,textview出现在屏幕的左上角。我希望它出现在图像按钮上。

LinearLayout LinearLayout = new LinearLayout(this); 
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeLayoutParams;  

Button[] btn = new Button[1];   
btn[0] = new Button(this);
btn[0].setId(1);
btn[0].setGravity(Gravity.CENTER);
btn[0].setText("text");        
btn[0].setBackgroundResource(R.drawable.button_grey);
btn[0].setTextColor(Color.parseColor("#FFFFFF"));


relativeLayoutParams = new     RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                       RelativeLayout.LayoutParams.WRAP_CONTENT);

relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT | RelativeLayout.ALIGN_PARENT_TOP);

relativeLayoutParams.setMargins(20, 20, 15, 15);

relativeLayout.addView(btn[0], relativeLayoutParams);

ImageButton[] Imgbtn = new ImageButton[10];
Imgbtn[0] = new ImageButton(this);
Imgbtn[0].setId(2);   
Imgbtn[0].setBackgroundResource(R.drawable.box_round_corners); 
Imgbtn[0].setMaxHeight(200);
Imgbtn[0].setClickable(true);

relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                       RelativeLayout.LayoutParams.WRAP_CONTENT);


relativeLayoutParams.addRule(RelativeLayout.BELOW,btn[0].getId());
relativeLayoutParams.height = 100;    
relativeLayoutParams.setMargins(15, 0, 15, 10);
Imgbtn[0].setLayoutParams(relativeLayoutParams);

relativeLayout.addView(Imgbtn[0], relativeLayoutParams);

TextView[] txtview = new TextView[10];
txtview[0] = new TextView(this);
txtview[0].setId(3);
txtview[0].setTextColor(Color.parseColor("#000000"));
txtview[0].setText("text");  

relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                       RelativeLayout.LayoutParams.WRAP_CONTENT);

// relativeLayoutParams.addRule(RelativeLayout.ALIGN_LEFT | RelativeLayout.ALIGN_TOP);

relativeLayoutParams.addRule(RelativeLayout.BELOW,Imgbtn[0].getId());
relativeLayoutParams.height = 20;    
relativeLayoutParams.setMargins(5, 5, 5, 5);
txtview[0].setLayoutParams(relativeLayoutParams);

relativeLayout.addView(txtview[0], relativeLayoutParams);


android.widget.ScrollView ScrollV = new ScrollView(this); 
ScrollV.addView( relativeLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
addContentView(ScrollV, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 

1 个答案:

答案 0 :(得分:0)

尝试使用setLayoutParams()方法设置视图LayoutParams;

RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(width,height);
lp.topMargin=//what is your desired y coordinate
lp.leftMargin=//what is your desired x coordinate
lp.gravity=Gravity.NO_GRAVITY;
view.setLayoutParams(lp);

在我看来,FrameLayout更适合用于覆盖目的。