2017-06-21 70 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