0

我在循环中创建了一个带有动态按钮的活动。我得到一个列表并为列表中的每个元素创建一个按钮。之后按钮进入相同的活动,但每个按钮我想传递不同的字符串。

我在循环中这样做了:

    tour_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(TourListActivity.this,
                    TourMenuActivity.class);
            String info = tour.toString();
            intent.putExtra(TOUR_INFO, info);
            startActivity(intent);
        }
    }); 

但最后,所有按钮都得到相同的字符串(最后一个按钮的字符串)。

========================================= 完整代码:

   try {
        JsonObject respObject = jsonParser.parse(response).getAsJsonObject();
        JsonArray tourListArray = respObject.getAsJsonArray("tours");
        System.out.println("tourListArray: " + tourListArray.toString());

        for(int i = 0; i < tourListArray.size(); i++){
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            tour = tourListArray.get(i).getAsJsonObject();
            String tourCode = tour.get("tourcode").getAsString();
            Button tour_button = new Button(this);  
            tour_button.setText("Tour Code: " + tourCode);
            tour_button.setGravity(Gravity.LEFT);
            tour_button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(TourListActivity.this,
                            TourMenuActivity.class);
                    String info = tour.toString();
                    intent.putExtra(TOUR_INFO, info);
                    startActivity(intent);
                }
            }); 


            ll.addView(tour_button);

            LinearLayout yourLL = (LinearLayout) findViewById(R.id.Tours_List);
            yourLL.setOrientation(LinearLayout.VERTICAL);
            yourLL.addView(ll);  


        }
    } catch (JsonIOException e) {
        e.printStackTrace();
    } 
4

2 回答 2

2

创建按钮时,您可以:

 button.setTag(someString); 

然后在 onClick 你可以:

public void onClick(View v) {
        Intent intent = new Intent(TourListActivity.this,
                TourMenuActivity.class);
        String info = tour.toString();
        intent.putExtra(TOUR_INFO, ((Button)v).getTag());
        startActivity(intent);
    }
于 2013-02-11T15:17:20.963 回答
0

该变量tour在循环外定义,因此每个按钮共享同一个变量。在每次迭代中,您只需更改此变量存储的引用。

您可以在循环中创建最终变量,并在以下内容中使用它OnClickListener

for (int i = 0; i < tourListArray.size(); i++) {
    ...
    final String tourInfo = tour.info;
    tour_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(
                TourListActivity.this, 
                TourMenuActivity.class
            );
            intent.putExtra(TOUR_INFO, tourInfo);
            startActivity(intent);
        }
    });
    ...
}
于 2013-02-11T15:57:39.040 回答