代码改变世界

【android】代码中动态添加控件

2012-08-09 21:36  Loull  阅读(5701)  评论(0编辑  收藏  举报

需求:有时候在事先不能取得要多少控件,就在代码中动态添加

在Layout插入一个View:

<LinearLayout android:id="@+id/newsinfo_imgs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"></LinearLayout>

Java代码

private LinearLayout layout = null;
...
layout = (LinearLayout)findViewById(R.id.newsinfo_imgs);
...

ImageView imgView = getImageView();
imgView.setImageDrawable(drawable);
layout.addView(imgView);
private ImageView getImageView(){
    ImageView imgView = new ImageView(NewsInfoActivity.this);
    imgView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    imgView.setScaleType(ScaleType.CENTER_INSIDE);
    return imgView;
}

注意这行代码:

setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));