在Java代码中设置相对位置在某控件左侧
时间: 2024-02-25 17:53:49 浏览: 48
在Java代码中设置控件的相对位置,可以使用 `RelativeLayout.LayoutParams` 类。要将一个控件放在另一个控件的左侧,可以使用 `addRule()` 方法来设置 `RelativeLayout.ALIGN_LEFT` 规则。以下是一个示例代码:
```
RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
TextView textView2 = new TextView(this);
textView2.setId(R.id.textView2);
textView2.setText("TextView2");
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textView2.setLayoutParams(layoutParams2);
relativeLayout.addView(textView2);
TextView textView1 = new TextView(this);
textView1.setText("TextView1");
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
layoutParams1.addRule(RelativeLayout.ALIGN_LEFT, R.id.textView2);
textView1.setLayoutParams(layoutParams1);
relativeLayout.addView(textView1);
```
在这个例子中,`TextView2` 放在布局的左侧,因为它的 `layoutParams2` 对象设置了 `RelativeLayout.ALIGN_PARENT_LEFT` 规则。`TextView1` 的 `layoutParams1` 对象设置了 `RelativeLayout.ALIGN_LEFT` 规则,并且将 `R.id.textView2` 作为 `RelativeLayout.ALIGN_LEFT` 的第二个参数,这告诉 `TextView1` 在 `TextView2` 的左侧放置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)