簡體   English   中英

與適配器中的列表視圖上的項目進行交互

[英]Interacting with items on a listview within adapter

我有一個適配器,它接受String的數組列表,其中充滿了許多不同的名稱。 截至目前,它在列表視圖中正確顯示了所有名稱,但是我無法使復選框正常工作。 為了測試它,我做了一個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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM