android - 如何设置ImageView的LayoutParams

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

最佳答案

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

关于android - 如何设置ImageView的LayoutParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954616/

相关文章:

android - 使用 imageView.setImageBitmap 方法将位图设置为 ImageView 的背景

android - ImageView 显示灰色方 block 而不是图像

android - 如何在android中获取显示图像的宽度和高度?

android - 屏幕顶部的自定义 toast

java - Android 动画仅在第一次时有效

android - Android 如何知道应用程序针对哪个 API?

android - 如何将数据插入我的 Android 应用程序

android - 你如何使整个控件在 android 中可点击?

android - 从可见的缩放图像android获取位图

java.lang.ClassCastException : android. view.ViewGroup$LayoutParams 无法转换为 android.widget.RelativeLayout$LayoutParams