Android ListView.getChildAt(index)==null

其实我就是想实现这样的效果
这里写图片描述
就是初始化的时候,第一个字是红色的,背景是灰色的。但是点击一个后,这个会变红色,其他的还是默认的。这种效果很常见。

在onCreate()方法初始化时,我调用了这个方法ListView.getChildAt(index),程序就崩溃了。想不出来为什么。在网上找了一会也没找到合适的办法。

1 ListView还没绘制完成呢?
就加了下面这一段,发现还是不行。

  listView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                refreshListItemTvColor(0);
            }
        });

2 在ListView的getView()方法里面直接根据convertView添加监听。

 convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshListItemTvColor(convertView);
            }
        });

但是发现在内部类中操作convertView必须要把convertView用final来修饰。但是convertView不能用final修饰
这里写图片描述

3 我直接把第一个标记
在adpter中:

private boolean isInit = false;
 if (position == 0 && !isInit) {
            isInit = true;
            holder.nameTv.setTextColor(Color.RED);
            convertView.setBackgroundColor(ContextCompat.getColor(context, R.color.gray_background));
        }

也就是说当初始化并且position==0时,第一个item的字体和背景为选中状态。

在activity中

    /**
     * 改变颜色的tv的位置
     */
    private int colorPostion = 0;
    /**
     * 每次刷新一下左侧里列表的文字颜色
     *
     * @param position
     */
    private void refreshListItemTvColor(int position) {
        View convertView = listView.getChildAt(position);

        TextView textView = (TextView) convertView.findViewById(R.id.tv_menu_ver_item_name);
        textView.setTextColor(Color.RED);
        convertView.setBackgroundColor(ContextCompat.getColor(this, R.color.gray_background));


        //之前变色的tv要变会黑色
        View lastConvertView = listView.getChildAt(colorPostion);
        TextView lastTv = (TextView) lastConvertView.findViewById(R.id.tv_menu_ver_item_name);
        lastTv.setTextColor(Color.BLACK);
        lastConvertView.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

        colorPostion = position;
    }

每次点击都会记录此位置colorPostion 。且colorPostion 默认为位置为0。
虽然这样做很啰嗦。但是我没想到更好的办法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值