Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 17th, 2012  |  syntax: None  |  size: 1.90 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. setOnClickListener scope on dynamic added elements
  2. do
  3. {
  4.     EditText txt1 = new EditText(this);
  5.     EditText txt2 = new EditText(this);
  6.     Button showtxt = new Button(this);
  7.     linearLayout.addView(showtxt );
  8.     linearLayout.addView(txt1);
  9.     linearLayout.addView(txt2);
  10.     showtxt.setOnClickListener(new View.OnClickListener()
  11.     {
  12.        public void onClick(View v)
  13.        {
  14.            String aaa= txt1 .getText().toString();//HOW TO ACCESS txt1 and txt2 from here
  15.            String bbb= txt2 .getText().toString();
  16.        }
  17.     }
  18. }
  19. while(somecondition)
  20.        
  21. public class Example extends Activity {
  22.     EditText txt1;
  23.     EditText txt2;
  24.  
  25.     @Override
  26.     public void onCreate(Bundle savedInstanceState)
  27.     {
  28.         super.onCreate(savedInstanceState);
  29.         txt1 = new EditText(this);
  30.         txt2 = new EditText(this);
  31.         ...
  32.        
  33. do {
  34.     ...
  35.     // EditText[] array = { txt1, txt2 };
  36.     //  is the short version of
  37.     EditText[] array = new EditText[2];
  38.     array[0] = txt1;
  39.     array[1] = txt2;
  40.  
  41.     showtxt.setTag(array);
  42.     showtxt.setOnClickListener(new View.OnClickListener() {
  43.        public void onClick(View v) {
  44.            EditText[] array = (EditText[]) v.getTag();
  45.            String aaa = array[0].getText().toString();
  46.            String bbb = array[1].getText().toString();
  47.            Log.v("Example", aaa + " " + bbb);
  48.        }
  49.     });
  50. } while(some condition)
  51.        
  52. View row = new View(this); // or this could be another LinearLayout
  53. row.setBackgroundColor(0x0000ff);
  54.  
  55. // Create and add the Button and EditTexts to row, as in row.addView(showtxt), etc
  56. ...
  57. linearLayout.addView(row);
  58.  
  59. showtxt.setOnClickListener(new View.OnClickListener() {
  60.     public void onClick(View v) {
  61.         View row = v.getParent()
  62.         String aaa = ((EditText) row.getChildAt(1)).getText().toString();
  63.         String bbb = ((EditText) row.getChildAt(2)).getText().toString();
  64.         Log.v("Example", aaa + " " + bbb);
  65.     }
  66. });