RelativeLayout用代码实现布局

本文深入探讨了Android应用中使用XML布局创建视图的技巧与实践,包括如何利用RelativeLayout设置组件的位置关系,如使TextView1左对齐并位于其他组件左侧,TextView2右对齐并位于屏幕右侧等。通过实例代码解析,读者可以了解如何精确控制界面元素的布局,实现高效、美观的UI设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TextView txt1 = new TextView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

params.addRule(RelativeLayout.LEFT_OF, 1001);
txt1.setLayoutParams(params);

TextView txt2 = new TextView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams. WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
txt2.setLayoutParams(params2);
txt2.setText("obj");
txt2.setId(1001);

RelativeLayout layout1 = new RelativeLayout(this);
layout1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout1.addView(txt1);
layout1.addView(txt2);
setContentView(layout1);


对应的XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TextView
android:id="@+id/leftobj"
android:hint="left of the base"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_toLeftOf="@+id/base"
android:layout_height="wrap_content"></TextView>
<TextView
android:id="@+id/base"
android:text="obj"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="wrap_content"></TextView>
</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值