Adding a different putExtra to an intent for each

2019-09-19 17:46发布

问题:

I'm creating buttons dynamically to a linear layout and after a button is clicked it goes to a new activity. I want to pass along a string with information about which button was clicked with that activity as a putExtra. For some reason the intents that I add to the each buttons onClickListener get overwritten so it only sends the string of the last button and not the one that is clicked:

    LinearLayout l = (LinearLayout) findViewById(R.id.allOptions);

    for(int i=0; i<currentOptions.size(); i++){
        Button newButton = new Button(this);
        SortingGroup s = currentOptions.get(i);
        newButton.setText(s.getName());
        sortGroupName = s.getName();;
        newButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),CategorySelector.class);
                intent.putExtra("sorting_category_name",sortGroupName);
                startActivity(intent);
            }
        });
        l.addView(newButton);
    }

回答1:

Add the sortGroupname in ArrayList and setid() for buttons

ArrayList<String> names=new ArrayList<>();

set id for buttons

newButton.setId(i);

Add names to arrayList

names.add(s.getName());

OnClick Listener like this

@Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(),CategorySelector.class);
            intent.putExtra("sorting_category_name",names.get(v.getId()));
            startActivity(intent);
        }