以编程方式将多个视图添加到布局 - 只有一个视图可见

时间:2014-10-21 11:31:39

标签: android view add

问题是只有第一个视图可见。如果我在视图2之前添加视图1,则只能看到视图1。如果我在视图1之前添加视图2,则只能看到视图2。我确实尝试过setVisibility但是......没有运气:(

这是我的代码:

   LinearLayout ver_layout = new LinearLayout(this);
        ver_layout.setOrientation(LinearLayout.VERTICAL);

    //create an image view
    ImageView iv_ava = new ImageView(this);
    iv_ava.setImageResource(R.drawable.sss);
    // add it to my vertical layout
    ver_layout.addView(iv_ava, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    //create a text view
    TextView tv_name = new TextView(this);
    tv_name.setText("testing");
    //add it to my vertical layout
    ver_layout.addView(tv_name, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    //after adding 2 views to a vertical layout, I add that layout to a 
    //horizontal linear layout, which is a layout defined in xml
    LinearLayout hori_layout = (LinearLayout) view
            .findViewById(R.id.hori_layout);
    hori_layout.addView(ver_layout, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

1 个答案:

答案 0 :(得分:1)

经过几个小时查看我的代码,我意识到我导入了错误的LayoutParams。它应该是android.view.ViewGroup.LayoutParams而不是android.view.WindowManager.LayoutParams