android用代码布局替代xml布局

    xiaoxiao2022-06-29  46

    还是继续练习一下代码布局替代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。

    转载请注明原文地址: https://ju.6miu.com/read-1124824.html

    最新回复(0)