Set custom attributes programmatically in Android
<p>I have following custom attribute:</p>

<pre><code>&lt;declare-styleable name="BoxGridLayout"&gt;
        &lt;attr name="numColumns" format="integer" /&gt;
        &lt;attr name="numRows" format="integer" /&gt;
        &lt;attr name="separatorWidth" format="dimension" /&gt;
        &lt;attr name="separatorColor" format="color" /&gt;
        &lt;attr name="equalSpacing" format="boolean" /&gt;
    &lt;/declare-styleable&gt;
</code></pre>

<p>In a custom view we can get custom attributes as follows:</p>

<pre><code>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();
        }
</code></pre>

<p>And we need to set them in xml view layout: </p>

<pre><code>&lt;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"&gt;
</code></pre>

<p>How we can set these custom attributes programmatically in java code and not via custom namespace in xml?</p>