如何为ImageView设置LayoutParams

时间:2016-03-12 06:39:38

标签: android android-imageview layoutparams

我是Android新手。在我的应用中,我在FrameLayoutProgramatically课程中以编程方式创建了一个ImageView,但是当我使用setLayoutParams时 这个Imageview在那里显示错误。为什么我会收到这些错误?

我的FrameLayoutProgramatically课程:

public class FrameLayoutProgramatically extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Initializing imageView
        ImageView imageview = new ImageView(this);
        imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageview.setImageResource(R.drawable.nature);
        imageview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}

1 个答案:

答案 0 :(得分:3)

  

您需要指定需要使用的 LayoutParams ,必须使用   基于父布局,可以是任何东西    LinearLayout.LayoutParams RelativeLayout.LayoutParams FrameLayout.LayoutParams

RelativeLayout imageLayout = new RelativeLayout(this);

ImageView imageview = new ImageView(this);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageview.setImageResource(R.drawable.nature);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

imageLayout.addView(iv, lp);

imageview.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
imageLayout.addView(iv);