通过代码更改imageView宽度的问题

时间:2014-08-22 13:16:28

标签: android imageview

当我尝试更改imageView的宽度和高度时,应用程序崩溃

Java代码

final ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);
imageView1.setLayoutParams(new LinearLayout.LayoutParams(50, 50));

该应用程序崩溃说

08-22 15:14:33.670 E/AndroidRuntime(9917): 
java.lang.ClassCastException:android.widget.LinearLayout$LayoutParams cannot be cast to
android.widget.RelativeLayout$LayoutParams

1 个答案:

答案 0 :(得分:1)

更改

imageView1.setLayoutParams(new LinearLayout.LayoutParams(50, 50));

imageView1.setLayoutParams(new RelativeLayout.LayoutParams(50, 50));

发生错误的原因是你的ImageView在RelativeLayout中,但是你试图将它传递给LinearLayout params。

要保持其他布局修改,您可以尝试:

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView1.getLayoutParams();
layoutParams.height = 50;
layoutParams.width = 50;
imageView1.setLayoutParams(layoutParams);