从按钮单击检测listItem

时间:2015-06-01 13:51:35

标签: android listview button onclick position

我有一个带适配器的listView。每个项目都有两个按钮,我需要检测按钮按下的listItem。 这是我的代码:

List<String> mList = new ArrayList<>(Arrays.asList(mNames));
        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(
                getActivity(),
                R.layout.list_item_friends_new,
                R.id.friends_new_name,
                mList
        ){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                Button button = (Button) view.findViewById(R.id.btn_1);
                Button button1 = (Button)view.findViewById(R.id.btn_2);

                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "user #" + position + " was added", Toast.LENGTH_SHORT).show();
                    }
                });
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "user #" + position + " was removed", Toast.LENGTH_SHORT).show();
                    }
                });
                return view;
            }
        };

它向我显示了这个错误:

Error:(67, 47) error: local variable position is accessed from within inner class; needs to be declared final.

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以在使用帮助变量时解决此问题,该变量是最终的,并且具有position方法的public View getView(int position, View convertView, ViewGroup parent)参数的值。试试这样的事情:

final int selectedPosition = position;

此行位于以下行button1.setOnClickListener(new View.OnClickListener()之前,然后是您需要当前位置的位置,请使用selectedPosition变量而不是position非最终变量