0

我有一个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”变量中的值始终是列表视图中第一个(从上到下)对象的值(我假设它是最后一个实例)。如何获得我单击按钮的项目对象的值?

4

1 回答 1

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 的变量都可以从内部类中访问。

于 2013-09-10T11:52:38.957 回答