我使用CountDownTimer在View holder文本视图中显示剩余时间。我的代码结构如下:
Class Demo extends ArrayAdapter<ListItem>
{
ListItemHolder holder=new ListItemHolder();
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
holder.tv= (TextView)row.findViewById(R.id.tv_timer);
//Starting the countdown timer
return row;
}
static class ListItemHolder
{
TextView tv;
............
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
}
@Override
public void onTick(long millisUntilFinished) {
holder.tv.setText("time");
}
}
}
当我尝试将onTick值设置为列表项持有者内的文本视图时,应用程序会抛出空指针异常。谁能提出我在这里做错了什么?
提前致谢,
Timson
答案 0 :(得分:0)
getView中的convertView可能为null
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = vi.inflate(R.layout.your layout, null);
}
holder.tv= (TextView)row.findViewById(R.id.tv_timer);
//Starting the countdown timer
return row;
}
答案 1 :(得分:0)
你需要检查convertView是否为null,如果它是null,则需要对视图进行膨胀。
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
holder = new ListItemHolder();
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.your_layout, null);
holder.tv= (TextView)row.findViewById(R.id.tv_timer);
row.setTag(holder);
}else{
holder = (ListItemHolder) row.getTag();
}
//Starting the countdown timer
return row;
}