Search code examples
androidlistviewbuttononclickposition

detect listItem from button click


I have a listView with an adapter. Every item has two buttons, and i need to detect from which listItem the button was pressed. Here is my code:

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;
            }
        };

It shows me this error:

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

Please help me to fix this problem.


Solution

  • You could workaround it when you use a helping variable, which is final and has as value the value of the position parameter of the public View getView(int position, View convertView, ViewGroup parent) method. Try with something like this:

    final int selectedPosition = position;
    

    This line comes before the following line button1.setOnClickListener(new View.OnClickListener() and then where you need the current position, use the selectedPosition variable instead of the position variable which is not final