android - 在 customView 的 TypedArray 上获取 getString 的空指针异常

标签 android nullpointerexception android-custom-view typed-arrays

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

attrs.xml 文件包含:

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

示例和完整代码可见here .我面临的问题是,在可视化编辑器中,我在从 typedArray 获取字符串时不断收到空指针异常:

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

奇怪的是,如果我运行该应用程序,它运行良好(除了我在原始线程中报告的奇怪错误)。我试过修改 code of RomainGuy that has made a flowLayout ,我注意到那里也发生了同样的行为。

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

最佳答案

最后我找到了答案,通过查看 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();

关于android - 在 customView 的 TypedArray 上获取 getString 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12661972/

相关文章:

android - 将 Android NestedScrollView 水平滑动传递给父 View

Android 媒体查看器 SDK(相当于 iOS QLPreviewController)

java - 不规则的蓝牙传输速度?

java - 解析映射器 XML 时出错。原因 : java. lang.NullPointerException

java - 使用二叉树节点的 while 循环中出现 NullPointerException

Android - CircleView 内的 Google map

java - 无法解析方法 'setAdapter()'

android - 从 Android 设备连接到嵌入式蓝牙设备

java - 什么是NullPointerException,我该如何解决?

android - 单击事件不适用于 ListView 项目中的按钮