android用代码布局替代xml布局

还是继续练习一下代码布局替代xml布局。

用脚趾头想一想,xml中和代码中的属性也是一一对应的。但如何写呢?以属性最多的RelativeLayout为例,

Xml中是这样的

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.ali.yunos.androiddemo.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World! test ACTION_SEND"
        android:layout_centerHorizontal="true"/>

    <Button
        android:id="@+id/id_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="press me"/>

    <com.ali.yunos.androiddemo.MyView
        android:id="@+id/myView"
        android:layout_width="wrap_content"
        android:layout_height="100px"/>

</RelativeLayout>

RelativeLayout的特有属性,layout_centerHorizontal, layout_centerInParent等。那对应代码如何写?

比如相应的TextView控件这样写

mTv = new TextView(this);
mTv.setText("Hello World! test ACTION_SEND");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
mRLayout.addView(mTv, params);

看到没,其实很简单,就是设置一下布局参数LayoutParams。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值