[英]Dynamically setting height and width of a image view in android Fragment using LayoutParam
我有问题在Fragment活动中设置图像视图的高度和宽度。 我正在使用布局参数。 我的代码是这样的
View rootView = inflater.inflate(R.layout.book_details_layout, container, false);
pdf_image = ((ImageView) rootView.findViewById(R.id.pdf_img));
pdf_image.setLayoutParams(new LayoutParams(80, 80));
我在这段代码上遇到了崩溃。 logcat就像
E/AndroidRuntime(7517): java.lang.ClassCastException:android.view.ViewGroup$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
E/AndroidRuntime(7517): at android.widget.RelativeLayout$DependencyGraph.findRoots(RelativeLayout.java:1722)
E/AndroidRuntime(7517): at android.widget.RelativeLayout$DependencyGraph.getSortedViews(RelativeLayout.java:1667)
E/AndroidRuntime(7517): at android.widget.RelativeLayout.sortChildren(RelativeLayout.java:373)
E/AndroidRuntime(7517): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:381)
如何解决这个问题?
显然,您的父视图是RelativeLayout
并且您尝试在ImageView
上根据它使用LayoutParams
。 这可能会导致ClassCastException
。 试试这个:
pdf_image = ((ImageView) rootView.findViewById(R.id.pdf_img));
RelativeLayout.LayoutParams paramImage = new RelativeLayout.LayoutParams(80,80);
pdf_image.setLayoutParams(paramImage);
如果这有帮助,请告诉我。
您正在尝试使用常规LayoutParams
,而您应该使用RelativeLayout.LayoutParams
。 这是因为您的布局显然是RelativeLayout
。 尝试:
pdf_image.setLayoutParams(new RelativeLayout.LayoutParams(80, 80));
您可以指定宽度和高度 -
im.getLayoutParams().width=YOUR_WIDTH;
im.getLayoutParams().height=YOUR_HEIGHT;
简单的方法:
setContentView(R.id.main);
Display display = getWindowManager().getDefaultDisplay();
ImageView iv = (LinearLayout) findViewById(R.id.left);
int width = display.getWidth(); // ((display.getWidth()*20)/100)
int height = display.getHeight();// ((display.getHeight()*30)/100)
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);
尝试这个
//width & height are your default image
private void imageLayout() {
// TODO Auto-generated method stub
imageview = getResources().getDrawable(R.drawable.your_imageView);
height = imageview .getIntrinsicHeight();
width = imageview .getIntrinsicWidth();
}
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width,height);
imageView.setLayoutParams(params);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.