【问题标题】:Set custom attributes programmatically in Android在 Android 中以编程方式设置自定义属性
【发布时间】:2016-06-12 11:28:04
【问题描述】:

我有以下自定义属性:

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

【问题讨论】:

  • PadLayout 添加设置器不是一个选项吗?这就是人们通常会做的事情。
  • ?你的 PadLayout 是一个 customView,所以你需要在你的类中拥有这些属性。
  • 所有这些看起来都像是一个类成员变量。您是否尝试过 setter 方法来动态设置值然后重绘视图?

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


【解决方案1】:

您可以使用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);

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2011-03-15
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    相关资源
    最近更新 更多