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。
虽然这样做很啰嗦。但是我没想到更好的办法。

package com.yha.runtime.testitem; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.yha.runtime.log.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.yha.runtime.R; import com.yha.runtime.RunningBaseActivity; import com.yha.runtime.testitem.devices.InstrumentBluetooth; import com.yha.runtime.testitem.devices.InstrumentCamera; import com.yha.runtime.testitem.devices.InstrumentCompas; import com.yha.runtime.testitem.devices.InstrumentGPS; import com.yha.runtime.testitem.devices.InstrumentGSensor; import com.yha.runtime.testitem.devices.InstrumentGyro; import com.yha.runtime.testitem.devices.InstrumentLSensor; import com.yha.runtime.testitem.devices.InstrumentListener; import com.yha.runtime.testitem.devices.Instrument; import com.yha.runtime.testitem.devices.InstrumentPSensor; import com.yha.runtime.testitem.devices.InstrumentWiFi; import com.yha.runtime.util.Constants; import com.yha.runtime.util.Param; import com.yha.runtime.util.finshCallBack; public class InstrumentTest extends RunningBaseActivity implements InstrumentListener { private final int MSG_TEST_START = 1; private final int MSG_UPDATE_VIEW = 2; private final int MSG_TEST_TIMEOUT = 3; private String[] instrument_result; private final int INSTRUMENT_LIMIT_TIME = 2*60; private int mLoopCount = 0; private int mLoopTotalCount = 0; private Boolean mMessageSend = false; public final String FINISH_TEST = "com.yha.runtime.instrumenttest"; private ListView mListview; private InstrumentAdapter mInstrumentAdapter; private List<Instrument> InstrumentColloction = new ArrayList<Instrument>(); private final Handler mHandler = new MyHandler(this); private static class MyHandler extends Handler { private final WeakReference<InstrumentTest> mActivity; public MyHandler(InstrumentTest activity) { mActivity = new WeakReference<InstrumentTest>(activity); } @Override public void handleMessage(Message msg) { if (mActivity.get() == null) { return; } mActivity.get().processMessage(msg); } } public void processMessage(Message msg){ switch (msg.what) { case MSG_TEST_START: Log.i(TAG,"to start test Instrument"); startAllInstrument(); mMessageSend = true; break; case MSG_UPDATE_VIEW: Object object = msg.obj; int status = msg.arg1; if(status == Instrument.TEST_FAILED){ TestFinish(Constants.RESULT_FAIL); } mInstrumentAdapter.upateView(object, status); checkTestComplete(); break; default: Log.d(TAG, "to upate view .... default "); break; } } private void checkTestComplete() { Log.d(TAG,"checkTestComplete"); Instrument ins; int completeCount = 0; for(int i = 0;i<InstrumentColloction.size();i++){ ins = InstrumentColloction.get(i); if(!ins.isComplete()) { Log.d(TAG,"comName=" + ins.getInstrumentName()); break; } completeCount++; } if (mMessageSend &&(completeCount == InstrumentColloction.size())) { mMessageSend = false; mLoopCount++; Log.d(TAG, "cunrrent index:"+mLoopCount); if(mLoopCount < mLoopTotalCount){ mInstrumentAdapter.refreshView(); mHandler.sendEmptyMessageDelayed(MSG_TEST_START,Constants.DELAY_TWO_SECOND); }else{ this.TestFinish(Constants.RESULT_PASS); } } } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.instrument_list); initAllInstrument(); instrument_result = getResources().getStringArray(R.array.instrument_result); mListview = (ListView) findViewById(R.id.listView); mInstrumentAdapter = new InstrumentAdapter(getApplicationContext()); mListview.setAdapter(mInstrumentAdapter); mLoopCount = 0; mLoopTotalCount = (Integer) Param.getParameter(Param.INDEX_INSTRUMENT_NUMBER); mHandler.sendEmptyMessageDelayed(MSG_TEST_START,Constants.DELAY_TWO_SECOND); setTestDution(INSTRUMENT_LIMIT_TIME*mLoopTotalCount, FINISH_TEST,exitCallBack); } public finshCallBack exitCallBack = new finshCallBack () { public void exitTest(){ Instrument ins; for(int i = 0;i<InstrumentColloction.size();i++){ ins = InstrumentColloction.get(i); if(!ins.isComplete()) { ins.stop(); } } } }; private void initAllInstrument() { if(Param.TestParameter.isEmpty()){ Param.initTestParameter(mContext); Log.d(TAG,"Error init in RuntimeTestMain,now initTestParameter"); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_BT_SWITCH)) { InstrumentColloction.add(new InstrumentBluetooth(mContext)); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_WIFI_SWITCH)) { InstrumentColloction.add(new InstrumentWiFi(mContext)); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_GPS_SWITCH)) { InstrumentColloction.add(new InstrumentGPS(mContext)); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_SENSOR_P_SWITCH)) { InstrumentColloction.add(new InstrumentPSensor(mContext)); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_SENSOR_L_SWITCH)) { InstrumentColloction.add(new InstrumentLSensor(mContext)); } //ifdef VENDOR_EDIT //Qiang.Yang@ODM_HQ.AD.EngineerMode, 2023/02/22, delete GYRO test // if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_SENSOR_GYRO_SWITCH)) { // InstrumentColloction.add(new InstrumentGyro(mContext)); // } //endif /* VENDOR_EDIT */ if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_SENSOR_G_SWITCH)) { InstrumentColloction.add(new InstrumentGSensor(mContext)); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_SENSOR_COMPASS_SWITCH)) { InstrumentColloction.add(new InstrumentCompas(mContext)); } if((Boolean)Param.getParameter(Param.INDEX_INSTRUMENT_CAMERA_SWITCH)) { InstrumentColloction.add(new InstrumentCamera(mContext)); } } private void startAllInstrument() { for(int i = 0;i < InstrumentColloction.size();i++) { Instrument ins = InstrumentColloction.get(i); ins.setListener(this); ins.start(); } } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); Log.d(TAG,"onResume"); } @Override protected void onDestroy() { // TODO Auto-generated method stub mHandler.removeCallbacksAndMessages(null); super.onDestroy(); } @Override public void updateView(Object object, int status) { Message msg = new Message(); msg.obj = object; msg.arg1 = status; msg.what = MSG_UPDATE_VIEW; mHandler.sendMessageDelayed(msg, Constants.DELAY_ONE_SECOND); } class InstrumentAdapter extends BaseAdapter { private LayoutInflater mInflater; public InstrumentAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } @Override public int getCount() { int count = InstrumentColloction.size(); return count; } @Override public Object getItem(int position) { return InstrumentColloction.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh = new ViewHolder(); if (convertView == null) { convertView = mInflater.inflate(R.layout.instrument_item, null); vh.instrument_name = (TextView) convertView.findViewById(R.id.item_name); vh.instrument_result = (TextView) convertView.findViewById(R.id.item_result); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } vh.instrument_name.setText(InstrumentColloction.get(position).getInstrumentName()); vh.instrument_result.setText(instrument_result[0]); return convertView; } public void upateView(Object obj, int status) { int index = InstrumentColloction.indexOf(obj); View view = mListview.getChildAt(index); if (view == null) { Log.d(TAG, "view == null,index =" + index); return; } if (obj == null) { Log.d(TAG, "obj == null,index =" + index); return; } ViewHolder holder = (ViewHolder) view.getTag(); holder.instrument_result = (TextView) view.findViewById(R.id.item_result); holder.instrument_name = (TextView) view.findViewById(R.id.item_name); holder.instrument_name.setText(((Instrument)obj).getInstrumentName()); holder.instrument_result.setText(instrument_result[status]); if(Instrument.TEST_SUCCESS == status){ holder.instrument_result.setTextColor(Color.GREEN); }else{ holder.instrument_result.setTextColor(Color.RED); } } private void refreshView(){ for(int i = 0;i < InstrumentColloction.size();i++){ View view = mListview.getChildAt(i); ViewHolder holder = (ViewHolder) view.getTag(); holder.instrument_result.setTextColor(Color.BLACK); holder.instrument_result.setText(instrument_result[0]); } } private final class ViewHolder { public TextView instrument_name; public TextView instrument_result; } } }
最新发布
06-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值