我正在尝试以编程方式对齐 RelativeLayout 中的一些元素,但我遇到了一些问题。即使我恭敬地设置它们,我的所有 TextView 元素都与左上角对齐。这是我的屏幕截图:
这是我的代码(this
是RelativeLayout):
title = new TextView(context);
date = new TextView(context);
rating = new RatingBar(context);
saleImage = new ImageView(context);
arrowImage = new ImageView(context);
RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
this.setBackgroundResource(R.drawable.list_selector);
this.setLayoutParams(relativeLayoutParams);
this.setClickable(true);
relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
saleImage.setLayoutParams(relativeLayoutParams);
saleImage.setImageResource(R.drawable.rihanna);
this.addView(saleImage);
relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
relativeLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
arrowImage.setImageResource(R.drawable.arrow);
arrowImage.setLayoutParams(relativeLayoutParams);
this.addView(arrowImage);
relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
relativeLayoutParams.addRule(RelativeLayout.RIGHT_OF, saleImage.getId());
title.setLayoutParams(relativeLayoutParams);
title.setTextAppearance(context, android.R.style.TextAppearance_Medium);
title.setText("Sale title");
this.addView(title);
relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
relativeLayoutParams.setMargins(0, 0, 26, 0);
relativeLayoutParams.addRule(RelativeLayout.LEFT_OF, arrowImage.getId());
date.setTextAppearance(context, android.R.style.TextAppearance_Small);
date.setText("14.01.13 22:00");
this.addView(date);
似乎问题出在RelativeLayout.RIGHT_OF
andRelativeLayout.LEFT_OF
属性上。
这是活动代码:
public class MainPage extends Activity {
private LinearLayout test;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_sales);
test = (LinearLayout)findViewById(R.id.salesConteiner);
SaleRow row = new SaleRow(this);
test.addView(row);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_page, menu);
return true;
}
}
有什么我错过的吗?谢谢!!!