4

I've created a new customized view that is intended to replace the weights mechanism of linearLayout. I've added some styles attributes that can be used straight within the layout xml file.

The attrs.xml file contains:

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

An example and full code can be seen here. The problem I'm facing is that in the visual editor, I keep getting a null pointer exception where I'm getting the string from the typedArray:

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

The weird thing is that if i run the app, it runs fine (except for the weird bugs I've reported in the original thread). I've tried to modify the code of RomainGuy that has made a flowLayout , and I've noticed the same behavior occurs there too.

Can anyone please tell me what I should do? How come it doesn't work?

2 Answers 2

3

finally i've found the answer , by looking at the android code at:

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

in order to get the text , you need to go over all of the attributes and use getText , for example :

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();
Sign up to request clarification or add additional context in comments.

Comments

1

you should check TypedArray.hasValue() before assign :

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);
}

1 Comment

Haha this was from 2012... Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.