在Android中以编程方式设置自定义属性

时间:2016-02-29 12:15:09

标签: android android-layout android-custom-view

我有以下自定义属性:

<declare-styleable name="BoxGridLayout">
        <attr name="numColumns" format="integer" />
        <attr name="numRows" format="integer" />
        <attr name="separatorWidth" format="dimension" />
        <attr name="separatorColor" format="color" />
        <attr name="equalSpacing" format="boolean" />
    </declare-styleable>

在自定义视图中,我们可以按如下方式获取自定义属性:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.BoxGridLayout,
                0,
                defStyleAttr);

        try {
            mStrokeWidth = a.getDimensionPixelSize(R.styleable.BoxGridLayout_separatorWidth, DEFAULT_STROKE_WIDTH);
            mStrokeColor = a.getColor(R.styleable.BoxGridLayout_separatorColor, DEFAULT_COLOR);
            mColumnCount = a.getInteger(R.styleable.BoxGridLayout_numColumns, DEFAULT_COLUMN_COUNT);
            mRowCount = a.getInteger(R.styleable.BoxGridLayout_numRows, DEFAULT_ROW_COUNT);
            mEqualSpacing = a.getBoolean(R.styleable.BoxGridLayout_equalSpacing, DEFAULT_EQUAL_SPACING);
        } finally {
            a.recycle();
        }

我们需要在xml视图布局中设置它们:

<com.github.ali.android.client.customview.view.PadLayout
        android:id="@+id/padLayout"
        style="@style/PadLayoutStyle"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        custom:numColumns="3"
        custom:numRows="4"
        custom:separatorColor="@color/dialer_theme_color"
        custom:separatorWidth="1dp">

我们如何在java代码中以编程方式设置这些自定义属性,而不是通过xml中的自定义命名空间?

1 个答案:

答案 0 :(得分:-3)

您可以使用LayoutParams。例如:

INFO