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

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

在自定义 View 中我们可以获取自定义属性如下:

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 View 布局中设置它们:

<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 中的自定义命名空间?

最佳答案

可以使用LayoutParams。例如:

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

关于android - 在 Android 中以编程方式设置自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699309/

相关文章:

android - 使用参数以编程方式添加按钮?

android - 是否可以在 Android 中创建没有 xml 的 View ?

android - 我的自定义 View 没有显示,我应该如何修复它?

android - DecorView 子框架布局在设备上不同

android - 无法构建 React Native 0.59.8 android.support.v4.net.ConnectivityManagerCompat

android - 错误 :Could not run build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-3.3-all.zip'

android - TextInput flexDirection :row not working in React-Native

android - 垂直 LinearLayout 的分隔线?

android - 如何从自定义 View 访问宿主 fragment 的生命周期范围?

android - 如何在候选 View 上显示候选 View 和回收器选项卡 View 位置?