Search code examples
androiddynamicandroid-edittextandroid-togglebutton

How do I know which dynamic Toggle Button was clicked in android


I am creating 10 editText and 10 Toggle Button dynamically in android. I have done this part, but I want some more advancements in it. The snippet is like:

for(int i =0 ; i < 10; i++) {
     et=new EditText(context);
     et.setLayoutParams(lprams); 
     et.setKeyListener(null);
     et.setClickable(true);
     et.setId(1); 
     et.setText(lwfb.get(i));
     et.setFocusableInTouchMode(true);
     final ToggleButton tb = new ToggleButton(context);
     tb.setTextOn("ON");
     tb.setTextOff("OFF");
     tb.setChecked(true);
     tb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

     ll.addView(et);
     ll.addView(tb);

     tb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             if(tb.isChecked()){
                 //Button is ON
             } else {
                 //Button is OFF
             }    
        }
    });
}

Where ll is the Dynamic LinearLayout variable.

I want to achieve two things:

  1. Display both Edit Text and Toggle Button of same index in same line.
  2. In place of //Button is ON/OFF I want to display button [i] is ON/OFF.

Solution

  • ll has probably a vertical orientation, which means, that the items added to the layout will appear one under another. To put the EditText and the ToggleButton in the same line, you have to put them in another layout - you can use another LinearLayout with horizontal orientation. Then instead of adding EditText and ToggleButton directly to ll, you add them to this new layout and then you add this new layout to ll.

    LinearLayout line = new LinearLayout(context);
    line.setOrientation(LinearLayout.HORIZONTAL);
    line.addView(et);
    line.addView(tb);
    ll.addView(line);
    

    You might also want to set layout parameters and other things to make some alignments.