- 上效果图
“花花”显示在左侧 | “花花”显示在右侧 |
---|---|
![]() | ![]() |
- RelativeLayout内部没有
setAbove
,setBelow
这样的设置,那么,如果想修改子view的位置,该怎么用代码控制?
RelativeLayout使用LayoutParams来控制位置的, RelativeLayout.LayoutParams中有个addRule()
。效果图代码如下:
public class MainActivity extends AppCompatActivity {
TextView tv;
Button btn1, btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
tv = findViewById(R.id.tv);
}
boolean b = false;
public void change(View view) {
if (b) {
btn1.setVisibility(View.GONE);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
lp.addRule(RelativeLayout.ABOVE, R.id.btn2);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
tv.setLayoutParams(lp);
b = false;
} else {
btn1.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
lp.addRule(RelativeLayout.ABOVE, R.id.btn1);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,0);
tv.setLayoutParams(lp);
b = true;
}
}
}
布局代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="花花"
android:layout_above="@id/btn2"
android:layout_alignParentRight="true"
/>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:visibility="gone"
android:text="可隐藏" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="固定显示" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="change"
android:text="test"
/>
</RelativeLayout>