如果我改变了任何开关状态,DatabaseReference
第一次没有从前一个值改变...如果我再次改变相同的开关状态它会完美地工作。这是我的代码:
public sigAdapter(Context context, String[] web, Integer[] imageId) {
super(context, R.layout.list, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
DatabaseReference databaseReference1 = database.getReference("data").child(web[position1].replace("/",""));
databaseReference=databaseReference1.child("Switch");
ViewHolder viewHolder=new ViewHolder();
View listItemView = view;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list, parent, false);
viewHolder.txtTitle = (TextView) listItemView.findViewById(R.id.text_view);
viewHolder.imageView = (ImageView) listItemView.findViewById(R.id.image_view);
viewHolder.switch1 = (Switch) listItemView.findViewById(R.id.switch_button);
final ViewHolder finalViewHolder = viewHolder;
viewHolder.switch1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
position1 = (Integer)v.getTag();
finalViewHolder.switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
DatabaseReference databaseReference1=database.getReference("data").child(web[position1].replace("/",""));
DatabaseReference databaseReference2=databaseReference1.child("Switch");
if (isChecked){
databaseReference2.setValue("On");
}else {
databaseReference2.setValue("Off");
}
}
});
}
});
listItemView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)listItemView.getTag();
}
viewHolder.switch1.setTag(position);
viewHolder.txtTitle.setText(web[position]);
viewHolder.imageView.setImageResource(imageId[position]);
return listItemView;
}
答案 0 :(得分:0)
因为您在OnCheckedChangeListener
中设置了OnClickListener
;所以onCheckChanged()
方法只有在第一次点击后才会被称为( on 第一次点击)。
只需从头开始使用OnCheckedChangeListener
。
viewHolder.switch1 = (Switch) listItemView.findViewById(R.id.switch_button);
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
position1 = (Integer) buttonView.getTag();
DatabaseReference databaseReference1 = database.getReference("data").child(web[position1].replace("/",""));
DatabaseReference databaseReference2 = databaseReference1.child("Switch");
if (isChecked){
databaseReference2.setValue("On");
} else {
databaseReference2.setValue("Off");
}
}
}