RelativeLayout title_bg = (RelativeLayout)FTU_Bluetooth.this.findViewById(R.id.titlebar);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0x55);
title_bg.setLayoutParams(params);
如果用RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(int, int),则会报Exception: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams
这是因为在这里的RelativeLayout在xml里是套在LinearLayout里的,必须建立父控件的LayoutParams。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" > <RelativeLayout android:id="@+id/titlebar" android:background="@drawable/main_title" android:layout_width="fill_parent" android:layout_height="66dp" >
--------------------------------------------------------------------------
下面转帖壮志凌云的博客: http://sunjilife.blog.51cto.com/3430901/1159639
在android中用代码动态添加组件或者改变某种布局(组件)的高度时,会遇到如题所示的类转换异常。
These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
So basically, if you are adding a view to another, you MUST set the LayoutParams of the view to the LayoutParams type that the parent uses, or you will get a runtime error.
如果你要将一个view添加到另一个布局中或者为这个view重新设定宽高等布局属性,你为该View设置的布局参数类型与其父类所使用的布局参数类型一样。此外就是说若是最上层的布局,则不需要设定此项。android中提供的布局参数类型目前一共12种:ViewPager.LayoutParams,LinearLayout.LayoutParams,RelativeLayout.LayoutParams,TableLayout.LayoutParams等等。关于
LayoutParams的说明http://www.cnblogs.com/shaweng/archive/2012/07/10/2585134.html
比如:
按照上面的说法,那么若是底层布局是LinearLayout,那么添加view的时候指定的宽高参数就必然是Linear.Layout
Params,可我在尝试过程中发现使用ViewGroup.LayoutParams,RelativeLayout.Params也可以运行,且不会出错,以下是代码:
经过试验,新增加的TextView的布局参数使用LinearLayout.LayoutParams,RelativeLayout.LayoutParams,ViewGroup.LayoutParams都是可以正确显示的,不相信的朋友,自己也可以试试看。至于这到底是什么原因呢,我目前也不清楚,希望有知道的朋友留言指教一下,谢谢