如何以编程方式将ImageView添加到布局中

时间:2014-08-01 08:21:47

标签: android

将ImageView添加到Layout时遇到问题。这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);


    RelativeLayout layout=(RelativeLayout)findViewById(R.id.relative);
    ImageView picture = new ImageView(this);
    picture.setImageResource(R.drawable.picture1);
    layout.addView(picture);
}

Eclipse中没有显示错误,但是当我在设备中运行时,程序崩溃。

1 个答案:

答案 0 :(得分:0)

您正在获取相对布局的NPE作为片段。所以请在onCreateView这样的片段中得到它:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.place_holder_fragment, container, false);
    RelativeLayout layout= (RelativeLayout) view.findViewById(R.id.relative);
    ImageView picture = new ImageView(this);
    picture.setImageResource(R.drawable.picture1);
    layout.addView(picture);
    return view;
}

Creating fragment