假设我在RelativeLayout
中有两个按钮。顶部标有“一个”的按钮和“一个”下面标有“三”的按钮。布局定义如下。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/mainContainer"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvOne"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="One" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvThree"
android:layout_centerHorizontal="true"
android:layout_below="@id/tvOne"
android:text="Three" />
</RelativeLayout>
因此,我在onCreate
的{{1}}中编写了一些代码,以动态创建MainActivity
,并将其插入到1到3之间。但它没有用。有什么我想念的吗?我创建这个问题是我所遇到的更大问题的简化版本,所以我不能接受清除布局并动态插入一个二和三。
Button
答案 0 :(得分:3)
我正在检查工作代码。
public class Main extends Activity {
Context ctx;
RelativeLayout rlayMainContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
rlayMainContainer = (RelativeLayout) findViewById(R.id.mainContainer);
Button one = (Button) findViewById(R.id.tvOne);
Button three = (Button) findViewById(R.id.tvThree);
// adding button two dynamically
Button two = new Button(ctx);
two.setText("hello");
two.setId(12);
RelativeLayout.LayoutParams lpSecond = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lpSecond.addRule(RelativeLayout.CENTER_HORIZONTAL);
lpSecond.addRule(RelativeLayout.BELOW, one.getId());
rlayMainContainer.addView(two, lpSecond);
//align button three below button two
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) three
.getLayoutParams();
params.addRule(RelativeLayout.BELOW, two.getId());
three.setLayoutParams(params);
}
}
答案 1 :(得分:0)
实际上,“两个”按钮就在那里,但你看不到因为它的高度= 0。 这些代码行使“两个”按钮的高度= 0
params.addRule(RelativeLayout.BELOW, one.getId());
params.addRule(RelativeLayout.ABOVE, three.getId());
是的,“两个”按钮layoutParams表示它必须介于“一”和“三”之间,但这些按钮之间没有剩余空间 - &gt;没有高度。
要解决此问题,您需要删除设置“两个”高于“三”的行并添加代码以指示“三”现在低于“两个”
final int WC = RelativeLayout.LayoutParams.WRAP_CONTENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
WC, WC);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, one.getId());
two.setLayoutParams(params);
// Add button number two to the activity.
RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainContainer);
rl.addView(two);
two.setId(1);
params = (LayoutParams) three.getLayoutParams();
params.addRule(RelativeLayout.BELOW, two.getId());
three.setLayoutParams(params);