2017-06-21 73 views
0

我正在创建按钮动态线性布局,并在按钮被点击后,它去一个新的活动。我想传递一个字符串,其中包含有关哪个按钮被点击的信息作为putExtra。出于某种原因,我添加到每个按钮的意图onClickListener被覆盖,所以它仅发送最后一个按钮的字符串,而不是被点击的一个:向每个动态创建的按钮的意图添加不同的putExtra

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

回答

3

添加按钮

在ArrayList中的 sortGroupnamesetid()

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

组的ID为按钮

ñ ewButton.setId(ⅰ);

添加名称的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); 
     } 
+0

谢谢!这工作完美。我猜测我的问题是,即使每次创建新的intent时都不能在putExtra中为同一个标记设置不同的值? – Mike