我是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));
}
答案 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);