【问题标题】:Adding a different putExtra to an intent for each dynamically created button为每个动态创建的按钮添加不同的 putExtra
【发布时间】:2017-06-21 15:20:40
【问题描述】:

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

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

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

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

    ArrayList&lt;String&gt; names=new ArrayList&lt;&gt;();

    为按钮设置 ID

    newButton.setId(i);

    向数组列表添加名称

    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 中为同一个标签设置不同的值,即使我每次都创建一个新的意图?
    猜你喜欢
    • 1970-01-01
    • 2014-05-21
    • 2021-07-08
    • 1970-01-01
    • 2017-12-19
    • 2011-10-30
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多