[英]Dynamically setting height and width of a image view in android Fragment using LayoutParam
I have problem to set the height and width of a image view inside a Fragment activity. 我有问题在Fragment活动中设置图像视图的高度和宽度。 I am using the Layout Param.
我正在使用布局参数。 My code is like this
我的代码是这样的
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));
I am getting crash on this code. 我在这段代码上遇到了崩溃。 The logcat is like
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)
How to fix this? 如何解决这个问题?
Apparently your parent view is a RelativeLayout
and you try to use the LayoutParams
according to it on your ImageView
. 显然,您的父视图是
RelativeLayout
并且您尝试在ImageView
上根据它使用LayoutParams
。 This might cause a ClassCastException
. 这可能会导致
ClassCastException
。 Try this instead: 试试这个:
pdf_image = ((ImageView) rootView.findViewById(R.id.pdf_img));
RelativeLayout.LayoutParams paramImage = new RelativeLayout.LayoutParams(80,80);
pdf_image.setLayoutParams(paramImage);
Let me know if this helps. 如果这有帮助,请告诉我。
You are trying to use general LayoutParams
, while you should use RelativeLayout.LayoutParams
. 您正在尝试使用常规
LayoutParams
,而您应该使用RelativeLayout.LayoutParams
。 This is because your layout is apparently a RelativeLayout
. 这是因为您的布局显然是
RelativeLayout
。 Try: 尝试:
pdf_image.setLayoutParams(new RelativeLayout.LayoutParams(80, 80));
You can assign width & height as - 您可以指定宽度和高度 -
im.getLayoutParams().width=YOUR_WIDTH;
im.getLayoutParams().height=YOUR_HEIGHT;
Easy way to do it: 简单的方法:
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);
try this 尝试这个
//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.