Adding a different putExtra to an intent for each dynamically created button

99封情书 提交于 2019-12-25 14:48:27

问题


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


来源:https://stackoverflow.com/questions/44680170/adding-a-different-putextra-to-an-intent-for-each-dynamically-created-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!