A
A
Alexander2014-04-22 16:12:08
Android
Alexander, 2014-04-22 16:12:08

How to get the size of View element from attributes in android?

I use a custom View element based on RelativeLayout, in the constructor I get attributes, if the size is specified in - "dp", then it works fine, but if I set MATCH_PARENT, the program crashes during initialization, how to get the size if MATCH_PARENT is specified, 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't 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.(CustomView.java:26)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question