I use a custom View element based on RelativeLayout, I get attributes in the constructor, if the size is set to - "dp", then it works fine, but if I put MATCH_PARENT
program crashes during initialization, how to get the size if specified MATCH_PARENT
and not for example 150dp?
private void init(AttributeSet attrs, Context context) { int[] attrsArray = new int[] { android.R.attr.id, // 0 android.R.attr.layout_width, // 1 android.R.attr.layout_height // 2 }; final TypedArray typedArray = context.obtainStyledAttributes(attrs, attrsArray); try { // Получаем Id Id = typedArray.getResourceId(0, View.NO_ID); // Ширина m_nWidth = typedArray.getDimensionPixelSize(1, ViewGroup.LayoutParams.MATCH_PARENT); // Высота m_nHeight = typedArray.getDimensionPixelSize(2, ViewGroup.LayoutParams.MATCH_PARENT); } catch(Exception ex) { m_nWidth = 200; m_nHeight = 200; } finally { // Освобождаем ресурсы typedArray.recycle(); } }
Constructor:
public CustomView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, context); }
Log:
04-22 13: 38: 18.695: E / AndroidRuntime (1992): FATAL EXCEPTION: main java.lang.UnsupportedOperationException: Can not convert to dimension: type = 0x10 04-22 13: 38: 18.695: E / AndroidRuntime (1992 ): at android.content.res.TypedArray.getDimensionPixelSize (TypedArray.java:463) 04-22 13: 38: 18.695: E / AndroidRuntime (1992): at com.test.view.CustomView.init (CustomView.java: 63) 04-22 13: 38: 18.695: E / AndroidRuntime (1992): at com.test.view.CustomView. <Init> (CustomView.java:26)