2013-02-11 48 views
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); 
     } 
    }); 

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

======================================== full code:

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(); 
    } 
+1

你在哪里分配在'tour'变量的值? – 2013-02-11 15:11:46

+0

我添加了代码 – Mike 2013-02-11 15:18:48

回答

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

这应该解决问题,如果字符串不同于按钮文本。 – onit 2013-02-11 15:21:58

+0

谢谢,它工作。 – Mike 2013-02-11 15:24:16

0

可变tour在循环之外定义,所以每个BU tton共享变量。 在每次迭代中,您只需更改由此变量存储的参考

,你可以创建你的循环内最终变量,并使用它的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); 
     } 
    }); 
    ... 
} 
相关问题