其实我就是想实现这样的效果
就是初始化的时候,第一个字是红色的,背景是灰色的。但是点击一个后,这个会变红色,其他的还是默认的。这种效果很常见。
在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。
虽然这样做很啰嗦。但是我没想到更好的办法。
115

被折叠的 条评论
为什么被折叠?



