I have problem to set the height and width of a image view inside a Fragment activity. 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
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
. This might cause a 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
. This is because your layout is apparently a 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.