简体   繁体   English

以编程方式创建的ImageButtons中定义的putExtra数据仅看到最后一个值?

[英]putExtra data defined in programatically created ImageButtons only sees last value?

I have programatically defined a set of imagebuttons in a for loop. 我已经在for循环中以编程方式定义了一组imagebuttons。 For each button, I defined its setOnClickListener function which will put some data in the intent and then switch activity. 对于每个按钮,我定义了其setOnClickListener函数,该函数会将一些数据放入意图中,然后切换活动。 However, it seems like no matter which button I clicked on, the extra data retrieved is set the the last value int he for loop. 但是,似乎无论我单击哪个按钮,检索到的额外数据都将设置为for循环的最后一个值。 See code here: 在这里查看代码:

public void onCreate(Bundle savedInstanceState) {
   <...>

        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlayout);

        for (int i=1; i<=maxMapLoc; i++ ) {
            mapLocation = i;
            ImageButton btnMapLoc = new ImageButton(FirstActivity.this);
            RelativeLayout.LayoutParams vp = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            btnMapLoc.setLayoutParams(vp);
            btnMapLoc.setBackgroundColor(Color.TRANSPARENT);
            btnMapLoc.requestLayout();
            String imgName = "map_loc_" + mapLocation;                
            int id = getResources().getIdentifier(imgName,"drawable",getPackageName());
            btnMapLoc.setImageResource(id);
            int imgMapLoc = 2000 + mapLocation;
            btnMapLoc.setId(imgMapLoc);
            rl.addView(btnMapLoc, vp);

            btnMapLoc.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                    intent.putExtra("MapLocation", mapLocation);

                    startActivity(intent);

                }
            });

Any idea what I did wrong? 知道我做错了什么吗?

Thanks. 谢谢。

You could add a tag to your button with the current mapLocation value. 您可以将带有当前mapLocation值的标签添加到按钮。

btnMapLoc.setTag(i);
...

// In onClick
    intent.putExtra("MapLocation", v.getTag());
    ...

The reason why you only get the last value of mapLocation is that the code inside your onClick() is run when the user pushes a button. 之所以只获得mapLocation的最后一个值,是因为onClick()中的代码是在用户按下按钮时运行的。 In other words your are querying mapLocation long after the loop built your buttons. 换句话说,在循环构建按钮之后很长时间,您正在查询mapLocation You need to create a reference to the current mapLocation in each loop iteration, like with the tag feature. 您需要在每次循环迭代中创建对当前mapLocation的引用,就像使用标记功能一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM