在android中用代码动态添加组件或者改变某种布局(组件)的高度时,会遇到如题所示的类转换异常。
如果你要将一个view添加到另一个布局中或者为这个view重新设定宽高等布局属性,你为该View设置的布局参数类型与其父类所使用的布局参数类型一样。此外就是说若是最上层的布局,则不需要设定此项。
比如:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<FrameLayout
android:id="@+id/FrameLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
若想在代码中动态改变FrameLayout的大小,应该这样写:
FrameLayout frameLayout=(FrameLayout) convertView.findViewById(R.id.FrameLayout01);
LinearLayout.LayoutParams ff=new LinearLayout.LayoutParams(LayoutParams.WRAP_C
ONTENT, height);
frameLayout.setLayoutParams(ff);
按照上面的说法,那么若是底层布局是LinearLayout,那么添加view的时候指定的宽高参数就必然是Linear.LayoutParams,可我在尝试过程中发现使用ViewGroup.LayoutParams,RelativeLayout.Params也可以运行,且不会出错,以下是代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_root_linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
RelativeLayout rootLayout;
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
rootLayout = (LinearLayout) findViewById(R.id.test_root_linearlayout);
LinearLayout.LayoutParams rootLinaerParams = new LinearLayout.LayoutParams(
100, 100);
ViewGroup.LayoutParams rootGroupParams = new LinearLayout.LayoutParams(
100, 100);
RelativeLayout.LayoutParams rootRelativeParams = new RelativeLayout.LayoutParams(
100, 100);
TextView testView = new TextView(this);
testView.setText("根布局测试动态添加组件并设置其大小");
testView.setLayoutParams(rootGroupParams);
rootLayout.addView(testView);
// rootLayout.addView(testView, viewParams);
}
经过试验,新增加的TextView的布局参数使用LinearLayout.LayoutParams,RelativeLayout.LayoutParams,ViewGroup.LayoutParams都是可以正确显示的,不相信的朋友,自己也可以试试看。至于这到底是什么原因呢,我目前也不清楚,希望有知道的朋友留言指教一下,谢谢
本文出自 “壮志凌云” 博客,请务必保留此出处http://sunjilife.blog.51cto.com/3430901/1159639