·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> Android动态添加View的问题解决方法

Android动态添加View的问题解决方法

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

后台代码
复制代码 代码如下:
    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。