setChecked不起作用

时间:2015-07-18 20:19:07

标签: android

我正在尝试使用切换按钮实现列表视图。一切顺利,问题在于切换按钮的方法long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; long run = 0; for(int i = 0; i < 10; ++i) { long start = System.currentTimeMillis(); for(int i = 0; i < keys.length; ++i) { obj.getElement(keys[i]); } long total = System.currentTimeMillis() - start; System.out.println(total/1000d + " seconds"); if(total < min) { min = time; } if(total > max) { max = time; } run += time; for(int i = 0; i < 50; ++i) { System.gc(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("min=" + min + " max=" + max); System.out.println("avg = " + (double)run/1000/keys.length); 。在向下到列表视图时,该按钮自动设置为自动关闭。我使用的是自定义适配器,这里是setChecked方法:

getView

问题是:

  

holder.tb.setChecked(器isChecked);

总是错误的。

我的public View getView(final int position, View convertView, ViewGroup parent) { final Holder holder = new Holder(); View rowView = inflater.inflate(R.layout.list_view_layout,null); holder.tv = (TextView) rowView.findViewById(R.id.tv_item); holder.tb = (ToggleButton) rowView.findViewById(R.id.tgl_status); holder.tv.setText(Name.get(position)); holder.tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // The toggle is enabled holder.tb.setChecked(isChecked); Toast.makeText(activity, Name.get(position) + "ON", Toast.LENGTH_LONG).show(); } else { // The toggle is disabled Toast.makeText(activity, "OFF", Toast.LENGTH_LONG).show(); holder.tb.setChecked(isChecked); } } }); rowView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(activity, "You Clicked "+Name.get(position), Toast.LENGTH_LONG).show(); } }); return rowView; } 文件是:

list_view_layout.xml

我正在使用一个使用此自定义适配器的片段。

1 个答案:

答案 0 :(得分:3)

我在这里看不到问题。

您正在检查/取消选中此ToggleButton IN CheckedChangeListener。也就是说:当您检查ToggleButton时,onCheckedChange会再次检查。你正在重复不需要的行动。

如果您实际上是想在Weather内的ArrayList Weathers中根据对象(我要说Adapter)进行检查,那么您应该去为:

if (weatherList.get(position).isChecked) { 
    holder.tb.setChecked(true);
} else { 
    holder.tb.setChecked(false);
}