Android Layout之二:RelativeLayout

本文详细介绍了Android中RelativeLayout的使用方法及特点。通过一个示例展示了如何使用XML定义布局,并在Activity中动态添加组件。

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



 Android Layout之二: RelativeLayout 

 

转载自: http://android.blog.51cto.com/268543/298345

 

 

 

 

 

 

 

相对定位布局

     这个布局比较易懂,但组件间容易存在依赖关系,“牵一发而动全身“,所以在确定组件间布局关系不会再变动时,可以考虑采用!

 

main.xml配置内容:

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout   xmlns:android="http://schemas.android.com/apk/res/android"   
	android:layout_width="wrap_content"   
	android:layout_height="wrap_content"   
	android:id="@+id/relativelayout">
<ImageView         
	android:id="@+id/image"         
	android:layout_width="wrap_content"          
	android:layout_height="wrap_content"         
	android:src="@drawable/icon"         
	/>
<TextView         
	android:id="@+id/text1"         
	android:layout_width="fill_parent"         
	android:layout_height="wrap_content"         
	android:text="Hello,this is a example of RelativeLayout."         
	android:layout_toRightOf="@id/image"         
	/>     
<Button         
	android:id="@+id/button1"         
	android:layout_width="fill_parent"         
	android:layout_height="wrap_content"         
	android:text="button1"         
	android:layout_toRightOf="@id/image"         
	android:layout_below="@id/text1"         
	/> 
</RelativeLayout>

 

 

 

Activity内容:

 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_relative_layout);
        
        //call method
        addIntoRelativeLayout();
    }
    //动态添加组件
    public void addIntoRelativeLayout(){
    	RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(             
    			ViewGroup.LayoutParams.FILL_PARENT, //width             
    			ViewGroup.LayoutParams.WRAP_CONTENT //height         
    			);          
    	//设置editText layout_below="@id/button1"         
    	lp.addRule(RelativeLayout.BELOW, R.id.button1);          
    	//设置editText layout_alignLeft="@id/image"         
    	lp.addRule(RelativeLayout.ALIGN_LEFT, R.id.image);          
    	((RelativeLayout) findViewById(R.id.relativelayout)).addView(new EditText(this), lp); 
    }

 

 

 

代码运行结果,如下图所示:

 


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值