为每个动态创建的按钮的意图添加不同的putExtra [英] Adding a different putExtra to an intent for each dynamically created button

查看:101
本文介绍了为每个动态创建的按钮的意图添加不同的putExtra的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态创建线性布局的按钮,单击按钮后将其转到新活动.我想传递一个字符串,其中包含有关在该活动中单击哪个按钮的信息,作为putExtra.由于某种原因,我添加到onClickListener的每个按钮上的意图被覆盖,因此它仅发送最后一个按钮的字符串,而不发送被单击的字符串:

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

推荐答案

在ArrayList中添加sortGroupname,并在按钮中添加setid()

Add the sortGroupname in ArrayList and setid() for buttons

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

设置按钮的ID

newButton.setId(i);

newButton.setId(i);

将名称添加到arrayList

names.add(s.getName());

像这样的OnClick监听器

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

这篇关于为每个动态创建的按钮的意图添加不同的putExtra的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆