2017-06-21 12 views
0

ボタンを線形レイアウトに動的に作成し、ボタンをクリックすると新しいアクティビティに移動します。私はputExtraとしてそのアクティビティでクリックされたボタンに関する情報を文字列に渡したいと思います。動的に作成された各ボタンのインテントに別の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()を追加します。それだけで最後のボタンの文字列ではなくクリックされたものを送るように、何らかの理由で、私は、各ボタンに追加する意図は上書きされますonClickListener

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

ボタン

nのセットID ewButton.setId(i);

この

@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

よう

names.add(s.getName()); 

のOnClickリスナーをArrayListに名前を追加します。ありがとうございます!それは完璧に働いた。私は私の問題は、新しい意図が私がそれを行うたびに作成された場合でも同じタグのputExtraで異なる値を設定することはできないと思いましたか? – Mike

関連する問題