Welcome

首页 / 移动开发 / Android / Android动态添加View的问题解决方法

后台代码
复制代码 代码如下:
    private void ChangeView()
    {
        ly.removeAllViews();
        LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.grid,null);
        GridView gridview = (GridView)layout.findViewById(R.id.gridview);
        gridview.setAdapter(new ItemAdapter(MainActivity.this));
        gridview.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView arg0, View arg1,
                    int arg2, long arg3) {
            }
            public void onNothingSelected(AdapterView arg0) {
            }
        });

        ly.addView(gridview);
    }

代码说明:

a). ly为main.xml中id为ContentView的LinearLayout,即需动态添加View的容器

b). ItemAdapter为Grid填充数据的辅助类

现象

正常

如果把grid.xml中GridView的代码直接复制粘贴到main.xml中LinearLayout容器内没有任何问题,布局正常。

不正常

如上动态添加android:layout_height="fill_parent"就失效,不管这里设置绝对数值如300dp也不行,GridView始终只显示有Item的内容,即容器内的View无法完全填充LinearLayout父容器。

 

三、 解决代码


就一行代码,不知道是Android的Bug还是怎么:
复制代码 代码如下:
ly.addView(gridview,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));

结束


这个问题烦了我两个小时+,不管怎么说还是解决了,开心ing。