【问题标题】:Alter AttributeSet values in android在 android 中更改 AttributeSet 值
【发布时间】:2015-10-03 12:29:32
【问题描述】:

我有自定义视图,它将属性集(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();
}

在 Fragment 类中,我将视图设置为

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

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

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

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

【问题讨论】:

  • 尝试为您设置LayoutParams CustomView。这样您就可以根据需要的条件修改其值。
  • @astuter CustomView 的值不仅是宽度,高度等。在视图中定义的值,例如颜色,showText,ShowColor,ShowGraph。等等

标签: android android-custom-view android-custom-attributes


【解决方案1】:

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

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

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

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

【讨论】:

  • 谢谢。这就是我正在寻找的。我需要修改自定义属性值,以便我可以使我的视图无效以反映。
  • 我建议您在 CustomView 中有一个方法来执行您想要的条件检查(如果它是通用的),并在此基础上通过属性的 setter 方法修改您的属性。希望这会有所帮助。
【解决方案2】:

假设您为名为 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
    }
}

【讨论】:

  • 在我的情况下阅读很好;问题是我需要根据条件更改值并仅刷新这些值。例如:我有十个属性,我只需要更改两个属性并且应该刷新视图。
  • 我想我不太明白,您在构建视图时收到的 AttributeSet 只是 Android 允许您读取 XML 写入值的方式,当然当我读到我的星星 = 5 时,还有什么在 textView 5 中写入我将在创建 set View 时设置此值
  • 还为您的变量添加 set / get 方法,在您的视图中表示此属性,以便您可以通过代码更改它们
【解决方案3】:

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

【讨论】:

  • 谢谢。我的问题是需要传递自定义参数,例如 Customview.angle、customView.isIntialized 之类的参数,这些参数之前在属性集 xml 中设置..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
相关资源
最近更新 更多