在 Android RelativeLayout 中 ,怎样点击一个button又出现另一个button
时间: 2024-02-06 20:09:46 浏览: 28
你可以在点击第一个按钮时,动态地向 RelativeLayout 中添加另一个按钮。具体步骤如下:
1. 在布局文件中定义一个 RelativeLayout,并在其中添加一个 Button:
```
<RelativeLayout
android:id="@+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"/>
</RelativeLayout>
```
2. 在代码中获取 RelativeLayout 和 Button 对象,并为 Button 设置点击事件:
```
RelativeLayout relativeLayout = findViewById(R.id.relative_layout);
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在 RelativeLayout 中添加另一个 Button
Button button2 = new Button(MainActivity.this);
button2.setText("New Button");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
params.addRule(RelativeLayout.BELOW, button1.getId());
relativeLayout.addView(button2, params);
}
});
```
3. 在点击事件中动态创建一个新的 Button,并设置它的文本和布局参数,然后添加到 RelativeLayout 中。这里的布局参数使用 RelativeLayout.LayoutParams,并设置了它的位置规则,使得新的 Button 位于第一个 Button 的下方。
注意:如果你需要在点击第二个 Button 时再出现第三个 Button,可以在第二个 Button 的点击事件中重复上述步骤即可。