3

我创建了一个新的自定义视图,旨在替换 linearLayout 的权重机制。我添加了一些可以直接在布局 xml 文件中使用的样式属性。

attrs.xml 文件包含:

<resources>
  <declare-styleable name="WeightedLayout_LayoutParams">
    <attr name="horizontalWeights" format="string" />
    <attr name="verticalWeights" format="string" />
  </declare-styleable>
</resources>

可以在此处查看示例和完整代码。我面临的问题是,在可视化编辑器中,我不断收到一个空指针异常,我从 typedArray 获取字符串:

final TypedArray arr=context.obtainStyledAttributes(attrs,R.styleable.WeightedLayout_LayoutParams);
//...
final String horizontalWeights=arr.getString(R.styleable.WeightedLayout_LayoutParams_horizontalWeights);

奇怪的是,如果我运行该应用程序,它运行良好(除了我在原始线程中报告的奇怪错误)。我试图修改制作 flowLayout 的 RomainGuy 的代码,并且我注意到那里也发生了相同的行为。

谁能告诉我我该怎么做?怎么行不通?

4

2 回答 2

2

最后我通过查看 android 代码找到了答案:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/widget/TextView.java?av=f

为了获取文本,您需要检查所有属性并使用 getText ,例如:

final TypedArray a=getContext().obtainStyledAttributes(attrs,R.styleable.WeightedLayout_LayoutParams);
int indexCount=a.getIndexCount();
for(int i=0;i<indexCount;++i)
  {
  final int attr=a.getIndex(i);
  if(attr==R.styleable.WeightedLayout_LayoutParams_horizontalWeights)
    _textToShow=a.getText(attr);
  }
a.recycle();
于 2012-11-12T19:57:30.177 回答
1

您应该在分配之前检查 TypedArray.hasValue() :

final TypedArray arr = context.obtainStyledAttributes(attrs,R.styleable.WeightedLayout_LayoutParams);
//...
if (arr.hasValue(R.styleable.WeightedLayout_LayoutParams_horizontalWeights)) {
final String horizontalWeights = arr.getString(R.styleable.WeightedLayout_LayoutParams_horizontalWeights);
}
于 2021-06-14T21:23:33.493 回答