与适配器

时间:2016-01-03 17:08:04

标签: android listview android-arrayadapter

我有一个接收器,它接收一个String的数组列表,其中包含许多不同的名称。截至目前,它正确显示列表视图中的所有名称,但我无法使复选框正常工作。为了测试它,我做了一个Toast,当复选框被cicked时,它会显示该人的名字。但是,它始终显示列表中最后一个人的姓名,无论我按哪个复选框。该复选框最终将更改特定人员的设置。我知道我误解了适配器是如何工作的,但我不知道在哪里。

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;
}

}

1 个答案:

答案 0 :(得分:0)

我完全理解你的问题我有同样的问题我无法找到更好的答案。尝试在列表中填写您的答案

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;
}