如题,有个GridView对象toolbarGrid,在onCreate里面放置了一些view对象。想在初始显示时设置某一项的背景色,例如以下方法:
toolbarGrid.getChildAt(index).setBackgroundResource(R.drawable.toolbar_menu_item);
但是,把这句即使不放在onCreate里面,放在onStart或者onResume里面,在run时都会报空指针错误。
但在启动以后,再设置就正常。
那么,初始启动时如何设置呢?

解决方案 »

  1.   

    toolbarGrid.getChildAt(index)这个是空指针么?
    如果你oncreate中已经创建出来了toolbarGrid,并且确认getChildAt不为空,那onStart里是不会有问题的
      

  2.   

    是报空指针错误。
    在onCreate里面已经创建了toolbarGrid,并且添加了view,但在onStrat里面还是报空指针错误。
    使用时没有加判断是否为null,我再试试。
    Thx!
      

  3.   

    1.onCreate中创建,toolbarGrid中添加了四个view
    // 创建底部菜单 Toolbar
    toolbarGrid = (GridView) findViewById(R.id.GridView_toolbar);
    toolbarGrid.setSelector(R.drawable.menu_itembg_pressed);
    toolbarGrid.setBackgroundResource(R.drawable.menu_bg2);// 设置背景
    toolbarGrid.setNumColumns(4);// 设置每行列数
    toolbarGrid.setGravity(Gravity.CENTER);// 位置居中
    toolbarGrid.setVerticalSpacing(10);// 垂直间隔
    toolbarGrid.setHorizontalSpacing(10);// 水平间隔
    toolbarGrid.setAdapter(getMenuAdapter(menu_toolbar_name_array,
    menu_toolbar_image_array));// 设置菜单Adapter2.onStart
    @Override
    protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    // set selected background for control bar button
    if (toolbarGrid != null) {
    Log.d(TAG, "screenStatus = " + screenStatus);
    Log.d(TAG, "toolbarGrid.getChildCount() = " + toolbarGrid.getChildCount()); // 结果为0,为什么是0,不是4?
    // toolbarGrid.getChildAt(screenStatus).setBackgroundResource(R.drawable.toolbar_menu_item);
    }
    }
      

  4.   

    你确定adapter中不是空的吗? 把onStart内的代码,放到button的按下事件中测试下
      

  5.   

    确定不为空,在其他button的onClick事件中
    Log.d(TAG, "toolbarGrid.getChildCount() = " + toolbarGrid.getChildCount()); // 结果为4,正常
      

  6.   

    还是没找到原因 ,暂时增加了一个handler,延迟一段时间后刷新解决。
      

  7.   

    还是没找到原因 ,暂时增加了一个handler,延迟一段时间后刷新解决。
      

  8.   

    getChildAt(),这方法在调用的时候 应该你的gridview中已经填充了内容了,不然就会报nullpointexception. 
    getChildAt(int position)返回的是当前屛内该位置的一个view对象。在传入这个position参数的时候也得注意下不然会报数组下标越界的 
      

  9.   

    建议楼主在geiview中去做  可以随意设置某项的背景色
      

  10.   

    gridview.setSelector();
    看看合不合适
      

  11.   

    在getView()方法中写上以下语句就可以了
    if(position==0){
        convertView.setBackgroundResource(R.drawable.bouttongbg2);
    }