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);
}
代码运行结果,如下图所示: