Set RelativeLayout layout params programmatically - throws ClassCastException

后端 未结 2 1770
小蘑菇
小蘑菇 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.

提交回复
热议问题