0

我在相对布局中放置了一个图像。如何在背景图像上放置一个小图像,并在图像旁边并排放置两个文本视图。任何帮助将不胜感激。唯一的事情是我想以编程方式执行此操作。我尝试过以下方式,但由于某种原因,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)); 
4

1 回答 1

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 是覆盖目的的更好选择。

于 2012-12-05T14:57:13.430 回答