我有一个Android ListView,每行内都有一个按钮。这是我的自定义ArrayAdapter的代码:
public class CheckInSArrayAdapter extends ArrayAdapter<JSONObject> {
CheckInFunctions checkFuns;
String check_id, watcher_id, user_id;
FragmentManager fm;
LayoutInflater inflater;
public CheckInSArrayAdapter(Context context, int textViewResourceId,
List<JSONObject> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getViewOptimize(position, convertView, parent);
}
public View getViewOptimize(int position, View convertView, ViewGroup parent) {
..... //various findViewById()
user_id = jObj.get("user_id").toString();
check_id = jObj.getString("check_id");
viewHolder.likeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!v.isActivated()){
if (checkFuns.like(check_id, watcher_id))
v.setActivated(true);
} else {
if (checkFuns.unlike(check_id, watcher_id))
v.setActivated(false);
}
}
});
return convertView;
}
private class ViewHolder {
.... //various variables
protected Button likeBtn;
}
}
所以这就是问题所在:当我点击按钮时,“check_id”变量中的值始终是listview中第一个(从上到下)对象的值(我假设它是最后一个实例)。我如何获得项目对象的值,我点击按钮?
答案 0 :(得分:3)
你可以这样做。
public class CheckInSArrayAdapter extends ArrayAdapter<JSONObject> {
CheckInFunctions checkFuns;
//String check_id, watcher_id, user_id; NOTE THIS
FragmentManager fm;
LayoutInflater inflater;
...
public View getViewOptimize(int position, View convertView, ViewGroup parent) {
..... //various findViewById()
final String user_id = jObj.get("user_id").toString(); //NOTE THIS
final String check_id = jObj.getString("check_id"); //AND THIS
viewHolder.likeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!v.isActivated()){
if (checkFuns.like(check_id, watcher_id))
v.setActivated(true);
} else {
if (checkFuns.unlike(check_id, watcher_id))
v.setActivated(false);
}
}
});
return convertView;
}
...
}
所有声明为final的变量都可以从内部类中访问。