我创建了一个RelativeLayout
,其中包含Button
和TextView
。使用此代码,TextView
会显示在Button
上方。我该怎么做,将Button
左边和TextView
对齐?缺什么?
这是我的代码:
final RelativeLayout topRelativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
topRelativeLayout.setLayoutParams(relativeLayoutParams);
mainLinearLayout.addView(topRelativeLayout);
final Button restartButton = new Button(this);
restartButton.setText(R.string.restartButton);
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
restartButton.setLayoutParams(buttonParams);
restartButton.setGravity(Gravity.LEFT);
topRelativeLayout.addView(restartButton);
final TextView timeTextView = new TextView(this);
timeTextView.setText(R.string.timeTextView);
timeTextView.setGravity(Gravity.RIGHT);
topRelativeLayout.addView(timeTextView);
谢谢!
答案 0 :(得分:1)
试试这个
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
button.setLayoutParams(buttonParams);
RelativeLayout.LayoutParams textviewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
textviewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
textView.setLayoutParams(textviewParams);
答案 1 :(得分:0)
如果这是您要实现的目标,则需要在该视图上使用setID方法为按钮或TextView设置ID。完成后,您可以将另一个视图的布局参数设置为相对于按钮的位置。像这样:
button.setId(1011);///OR WHATEVER INT YOU WANT
textView.setLayoutParams(new RelativeLayout.LayoutParams(width,height,left,top,right,bottomPadding,null,new int[][]{{RelatitiveLayout.ABOVE, button.getId()}});
要在RelativeLayout中设置视图的对齐方式,请使用:
button.setLayoutParams(new RelativeLayout.LayoutParams(width,height,0,0,0,0,new int[]{RelativeLayout.ALIGN_PARENT_RIGHT}));