我创建了一个新的自定义 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 代码:
为了获取文本,您需要遍历所有属性并使用 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/