在适配器中与列表视图上的项目交互

Interacting with items on a listview within adapter

我有一个适配器,它接受一个字符串数组列表,其中充满了一堆不同的名称。截至目前,它正确显示列表视图中的所有名称,但我无法使复选框正常工作。为了测试它,我制作了一个 Toast,当复选框被选中时应该显示该人的名字。但是,无论我按下哪个复选框,它总是显示列表中最后一个人的名字。该复选框最终将更改特定人员的设置。我知道我误解了适配器的工作原理,但我不确定在哪里。

public class SummonerAdapter extends ArrayAdapter<String> {
TextView summonerNameText;
String summonerName;
CheckBox checkBox;

public SummonerAdapter(Context context, ArrayList<String> summoners) {
    super(context, 0, summoners);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());     //inflates layout
    View theView = inflater.inflate(R.layout.list_layout, parent, false);
    summonerName = getItem(position);
    summonerNameText = (TextView) theView.findViewById(R.id.summonerName);
    summonerNameText.setText(summonerName);
    checkBox = (CheckBox) theView.findViewById(R.id.checkBox);
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Toast.makeText(getContext(), summonerNameText.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    });

    return theView;
}

}

我完全理解你的问题我遇到了同样的问题我找不到更好的答案。尝试将您的答案填入列表

public class SummonerAdapter extends ArrayAdapter<String> {
final TextView summonerNameText;
final String summonerName;
final CheckBox checkBox;

public SummonerAdapter(Context context, ArrayList<String> summoners) {
    super(context, 0, summoners);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());     //inflates layout
    final View theView = inflater.inflate(R.layout.list_layout, parent, false);
    summonerName = getItem(position);
    summonerNameText = (TextView) theView.findViewById(R.id.summonerName);
    summonerNameText.setText(summonerName);
    checkBox = (CheckBox) theView.findViewById(R.id.checkBox);
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Toast.makeText(getContext(), summonerNameText.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    });

    return theView;
}