当我检查一个切换按钮时,第五个切换按钮会在android中的listview中自动检查

时间:2015-02-23 18:24:59

标签: android listview state togglebutton

我有切换按钮的列表视图。当我选中第一个切换按钮时,第五个切换按钮会自动检查。当我检查第二个切换按钮时,第7个切换按钮被检查。当我取消选中第5个切换按钮时,它将保持空值。

以下是我的代码

public class CustomUsersAdapter extends ArrayAdapter<User> 
{

public CustomUsersAdapter(Context context, ArrayList<User> users)
    {

            super(context, 0, users);

    }

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
    //Get an instance of our cell holder                                                                         
     Holder holder;
     holder = new Holder();

    // Get the data item for this position
      User user = getItem(position);    

    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) 
    {
       convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);

        // Lookup view for data population
        holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
        holder.tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
        holder.tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);


        convertView.setTag(holder); //Add this
    }
    else
    {

       holder= (Holder) convertView.getTag();
    }

    holder.tvName.setText(user.name);
    holder.tvHome.setText(user.hometown);

    /** The clicked Item in the ListView */
    RelativeLayout rLayout = (RelativeLayout) convertView;

    /** Getting the toggle button corresponding to the clicked item */

    final ToggleButton tbt  = (ToggleButton) rLayout.getChildAt(2);

    tbt.setOnClickListener(new OnClickListener() {
        String homet;
        @Override
        public void onClick(View v) {

            // TODO Auto-generated method stub
             if (tbt.isChecked()) {
                 //tbt.setChecked(true);
                 ViewGroup parent = (ViewGroup) v.getParent();
                 TextView tvName = (TextView) parent.findViewById(R.id.tvName);
                 homet=tvName.getText().toString();

                    Toast.makeText(getContext(),homet+"Blocked", Toast.LENGTH_SHORT).show();
                } else {
                    tbt.setChecked(false);
                    Toast.makeText(getContext(),homet+ "Unblocked", Toast.LENGTH_SHORT).show();
                }
        }
        });

    // Return the completed view to render on screen
      return convertView;

        }
            //this holder class will be filled from the layout xml and attached to the row as a tag object


    private class Holder
    {
        TextView tvName;
        TextView tvHome;
        ToggleButton tgbtn,tg1;
    }
}

请帮帮我......

以及如何保存所有切换按钮状态,以便我可以使用该保存状态在应用重新打开时保留切换按钮的状态。

1 个答案:

答案 0 :(得分:0)

由于ListView回收机制,您的问题正在发生。 ListView回收其子行。为了更好地理解,请查看here 至于解决你的问题,很多人已经问过这个问题了。我能找到的最好的博客是this。您还可以查看thisthis