Android custom attribute settings

I have the following user attribute:

<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>

In the user view, we can get the user attributes as follows:

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

And we need to install them in an xml view layout:

<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">

How can we set these user attributes programmatically in java code, and not through the user namespace in xml?

+4
source share
1 answer

You can use LayoutParams. For instance:

LinearLayout parent=new LinearLayout(this);
    View child=new View(this);
    float density =getResources().getDisplayMetrics().density;
    LinearLayout.LayoutParams lllp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    lllp.setMargins((int) (10*density), (int) (10*density), (int) (10*density), (int) (10*density));
    lllp.gravity=Gravity.CENTER;
    child.setPadding((int) (10*density), (int) (10*density), (int) (10*density), (int) (10*density));
    child.setLayoutParams(lllp);
    parent.addView(child);
-3
source

All Articles