我正在創建一個帶有textview和複選框的自定義列表視圖項目。每當選中與用戶相對應的複選框時,我都希望在烤麪包片中看到他的名字。我已經使用了以下代碼:如何在列表視圖中獲取所選用戶名
mUserList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(ManualInviteActivity.this, position, Toast.LENGTH_SHORT).show();
Users1 user = (Users1) parent.getItemAtPosition(position);
if(user.isSelected()==true)
{
Toast.makeText(getBaseContext(), user.getName(), Toast.LENGTH_SHORT).show();
}
}
});
但是,當我切換複選框時,我沒有看到任何東西。這裏有什麼錯誤? 感謝 (isSelected和的getName是在用戶級的我自己的函數)
適配器代碼:
public class UserListAdapter extends ArrayAdapter<Users1> {
static Context context;
static int layoutResourceId;
Users1 data[] = null;
public UserListAdapter(Context context, int layoutResourceId, Users1[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public long getItemId(int position) {
return position;
}
static class UserHolder {
TextView txtTitle;
CheckBox cbxUser;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.user_name);
holder.cbxUser = (CheckBox) row.findViewById(R.id.user_checked);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
Users1 weather = data[position];
holder.txtTitle.setText(weather.title);
holder.cbxUser.setChecked(weather.isSelected());
// holder.txtTitle2.setText(weather.title2);
// holder.txtTitle2.setText(weather.title2);
// holder.txtTitle3.setText(weather.title3);
return row;
}
}
用戶1類:
public class Users1 {
public String title;
boolean selected = true;
public Users1()
{
super();
}
public Users1(String title,boolean selected) {
super();
this.selected = selected;
this.title = title;
}
public String getName() {
return title;
}
public void setName(String name) {
this.title = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
如果無法檢查列表項內。在
Nepster
而不是itemClickListener。使用適配器類內複選框的checkChangedListener。 – Nepster
是否解決了這個問題?在這裏使用listview會使事情變得更加困難,除非你單獨訪問全局複選框,如果你想單獨使用它,它不應該依賴於列表視圖的「getView()」方法 – user2450263