2

我有自定义视图,它将属性集(xml 值)作为构造函数值

public CustomView(Context context)  // No Attributes in this one.
{
    super(context);
    this(context, null, 0);
}

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this(context, attrs, 0)
}

public CustomView(Context context, AttributeSet attrs, int default_style) {
    super(context, attrs, default_style);
    readAttrs(context, attrs, defStyle);
    init();
}

在片段类中,我将视图设置为

CustomView customView = (CustomView) view.findViewById(R.id.customView); 

其中自定义视图包含各种值,例如高度、宽度、填充等。

我想根据所需条件修改这些值并将其设置回自定义视图。我在onDraw方法中放置了设置宽度高度代码并调用了无效视图。但是如果我在 CustomView 类中调用invalidate方法,上述方法将设置每次。如何克服这个问题,以便我只能在构造函数中传递修改后的属性集值。?

编辑:我需要修改在属性构造函数期间设置的视图值(使用新值初始化),以便我将获得具有新值的刷新视图。覆盖@OnDraw 或'Invalidate' 对我来说不是一个好的功能,在invalidate 里面我已经编写了将在每一秒间隔内执行的方法。

4

3 回答 3

2

我看到您CustomView可以有多个属性,并且您想根据某些条件修改其中一些属性并将其传递给构造函数。

设计自定义视图时的一些最佳实践:

  1. 如果您有自定义属性,请确保通过 setter 和 getter 公开它们。在您的 setter 方法中,调用invalidate();
  2. 不要尝试修改内部的任何属性onDraw()onMeasure()方法。
  3. 尽量避免为自定义视图编写自定义构造函数。

因此,解决您的问题的理想方法是实例化您的 CustomView,然后在外部(在您的 Activity 或 Fragment 中)修改属性,或者在内部有一个方法CustomView.java,然后在外部调用它。这样做仍然会为您提供您正在寻找的相同结果。

于 2015-10-13T04:26:01.677 回答
0

这可能不是您希望的解决方案,而是在您的 xml 中放置一个FrameLayout而不是CustomView,然后使用FrameLayout作为其父项以编程方式创建您的CustomView

于 2015-10-08T04:22:09.127 回答
0

因此,假设您为名为 StarsView 的视图声明了这样的自定义属性

<declare-styleable name="StarsView">
    <attr name="stars" format="integer" />
    <attr name="score" format="float" />
</declare-styleable>

你想从这样的东西中读取属性

<my.package..StarsView
    app:stars="5"
    app:score="4.6"

你在构造函数中这样做

public StarsView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if(attrs != null) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StarsView, defStyleAttr, 0);
        stars = Tools.MathEx.clamp(1, 10, a.getInt(R.styleable.StarsView_stars, 5));
        score =  (int)Math.floor(a.getFloat(R.styleable.StarsView_score, stars) * 2f);
        a.recycle(); // its important to call recycle after we are done
    }
}
于 2015-10-08T07:52:02.173 回答