Set RelativeLayout layout params programmatically - throws ClassCastException

后端 未结 2 1769
小蘑菇
小蘑菇 2020-12-13 21:24

I am inflating a RelativeLayout from XML and then attempting to programmatically sets its layout params and am receiving a ClassCastException.

Code:

         


        
相关标签:
2条回答
  • 2020-12-13 21:51

    The layout params have to be of the type of the parent. So if you are creating a RelativeLayout and adding it to a ListView, the layout params must be of type ListView.LayoutParams, not RelativeLayout.LayoutParams. The correct way to do it is to call inflate this way:

    inflate(R.layout.mylayout, theListView, false);

    This version of inflate() will correctly inflate the layout parameters (android:layout_*) defined in XML.

    0 讨论(0)
  • 2020-12-13 21:51

    If your view is in a ListView, you must use AbsListView.LayoutParams.

    See also: Unable to set margin of item in ListView using custom Adapter

    0 讨论(0)
提交回复
热议问题