使用LayoutParam在android Fragment中动态设置图像视图的高度和宽度

时间:2014-04-11 06:22:09

标签: java android android-activity

我在设置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)

如何解决这个问题?

5 个答案:

答案 0 :(得分:3)

显然您的父视图是RelativeLayout,并且您尝试在LayoutParams上根据它使用ImageView。这可能会导致ClassCastException。试试这个:

 pdf_image = ((ImageView) rootView.findViewById(R.id.pdf_img));
 RelativeLayout.LayoutParams paramImage = new RelativeLayout.LayoutParams(80,80);
 pdf_image.setLayoutParams(paramImage);

如果有帮助,请告诉我。

答案 1 :(得分:3)

您尝试使用常规LayoutParams,而应使用RelativeLayout.LayoutParams。这是因为您的布局显然是RelativeLayout。尝试:

pdf_image.setLayoutParams(new RelativeLayout.LayoutParams(80, 80));

答案 2 :(得分:2)

您可以指定宽度和宽度身高 -

im.getLayoutParams().width=YOUR_WIDTH;
im.getLayoutParams().height=YOUR_HEIGHT;

答案 3 :(得分:1)

简单的方法:

 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);

答案 4 :(得分:1)

试试这个

//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);