在自定义组件的AttributeSet中访问属性

5 浏览
0 Comments

在自定义组件的AttributeSet中访问属性

我有一个自定义组件,其中包含两个TextView,它们都有一个自定义的大小设置方法(这两个TextView的比例大约为1:2)。由于这是RelativeLayout的子类,它没有textSize属性,但我想知道是否可能仍然在XML实例化中设置android:textSize属性,并从AttributeSet中获取textSize属性,在构造函数中使用我的自定义setSize()方法。

我见过使用自定义属性来实现这一点的技巧,但如果我想获取已经存在于Android词典中的属性呢?

0
0 Comments

在自定义组件中访问属性集(AttributeSet)时可能会遇到问题,下面是问题的原因和解决方法:

问题原因:

问题是在自定义组件的构造函数中,无法直接访问Android命名空间中的属性。因此需要通过其他方法获取属性集中的属性值。

解决方法:

1. 方法一:使用getAttributeValue()方法获取属性值

在自定义组件的构造函数中,通过调用getAttributeValue()方法,传入Android命名空间的URL和属性名,即可获取属性值。然后可以对属性值进行相应的处理。

2. 方法二:使用自定义属性集

在自定义组件中,添加一个带有AttributeSet参数的构造函数。在构造函数中,调用TypedArray的obtainStyledAttributes()方法获取属性集中的属性值。然后可以根据属性值进行相应的处理。

为了使用自定义属性集,需要在attrs.xml文件中声明属性名称,并设置格式。然后在自定义组件的布局文件中使用这些属性,同时需要在布局文件中声明命名空间。

以上就是解决在自定义组件中访问属性集的问题的原因和方法。

0
0 Comments

从上面的内容可以看出,问题的出现原因是在自定义组件中访问属性时遇到了困难。为了解决这个问题,可以按照以下步骤进行操作。

1. 创建自定义属性

attrs.xml文件中创建(或添加)以下部分。注意dimension格式。

<resources>
    <declare-styleable name="CustomView">
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>

2. 在xml布局中设置属性

注意自定义的app命名空间。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <com.example.myproject.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:textSize="20sp" /> 
</RelativeLayout>

3. 在自定义视图中获取属性值

注意使用getDimensionPixelSize方法。在自定义视图中直接使用像素进行操作。如果需要转换为其他尺寸,请参考此答案

public class CustomView extends View {
    private float mTextSize; // 像素
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.CustomView, 0, 0);
        try {
            mTextSize = a.getDimensionPixelSize(R.styleable.CustomView_textSize, 0);
        } finally {
            a.recycle();
        }
    }
    /**
     *  大小以SP单位表示
     */
    public void setTextSize(int size) {
        mTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                size, getResources().getDisplayMetrics());
        mTextPaint.setTextSize(mTextSize);
        invalidate();
        requestLayout();
    }
    // ...
}

注意事项

0