如何为ImageView设置LayoutParams

How to set LayoutParams for ImageView

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

我的FrameLayoutProgramaticallyclass:

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

You need to specify which LayoutParams you need to use, it must be based on parent layout which can be anything LinearLayout.LayoutParams or RelativeLayout.LayoutParams or 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);