2013-04-24 2 views
1

Как я могу динамически обновлять свой макет, исходя из того, какой переключатель выбран? В настоящее время у меня есть весь мой код внутри oncreate, и кажется, что он только один раз проверяет, какой переключатель выбран, но как я могу его обновлять каждый раз, когда он изменяется?Android Изменение динамического представления с радиогруппами

вот мой код

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    LinearLayout mainLinear = new LinearLayout(this); 
    mainLinear.setOrientation(LinearLayout.VERTICAL); 
    LinearLayout ButtonLayout = new LinearLayout(this); 
    ButtonLayout.setOrientation(LinearLayout.HORIZONTAL); 
    ButtonLayout.setPadding(120, 15, 0, 0); 
    mainLinear.addView(ButtonLayout); 
    Button deleteSelectedButton = new Button(this); 
    deleteSelectedButton.setText("Delete Selected"); 
    Button backButton = new Button(this); 
    backButton.setText("Back"); 
    ButtonLayout.addView(deleteSelectedButton); 
    ButtonLayout.addView(backButton); 
    LinearLayout deleteAppointmentLayout = new LinearLayout(this); 
    deleteAppointmentLayout.setOrientation(LinearLayout.VERTICAL); 
    mainLinear.addView(deleteAppointmentLayout); 
    TextView dayLabel = new TextView(this); 
    dayLabel.setText("Days"); 
    dayLabel.setPadding(220, 10, 0, 0); 
    dayLabel.setTypeface(Typeface.DEFAULT_BOLD); 
    dayLabel.setTextSize(15); 
    deleteAppointmentLayout.addView(dayLabel); 
    RadioGroup radioGroup = new RadioGroup(this); 
    radioGroup.setOrientation(LinearLayout.HORIZONTAL); 
    radioGroup.setPadding(10, 0, 0, 0); 
    deleteAppointmentLayout.addView(radioGroup); 
    RadioButton mondayRadioButton = new RadioButton(this); 
    RadioButton tuesdayRadioButton = new RadioButton(this); 
    RadioButton wednesdayRadioButton = new RadioButton(this); 
    RadioButton thursdayRadioButton = new RadioButton(this); 
    RadioButton fridayRadioButton = new RadioButton(this); 
    mondayRadioButton.setText("Mon"); 
    tuesdayRadioButton.setText("Tue"); 
    wednesdayRadioButton.setText("Wed"); 
    thursdayRadioButton.setText("Thu"); 
    fridayRadioButton.setText("Fri"); 
    mondayRadioButton.setTextSize(12); 
    tuesdayRadioButton.setTextSize(12); 
    wednesdayRadioButton.setTextSize(12); 
    thursdayRadioButton.setTextSize(12); 
    fridayRadioButton.setTextSize(12); 
    mondayRadioButton.setChecked(true); 
    mondayRadioButton.setId(1); 
    tuesdayRadioButton.setId(2); 
    wednesdayRadioButton.setId(3); 
    thursdayRadioButton.setId(4); 
    fridayRadioButton.setId(5); 
    //OnClickListener radlistener; 
    //radioGroup.setOnClickListener(radlistener); 
    radioGroup.addView(mondayRadioButton); 
    radioGroup.addView(tuesdayRadioButton); 
    radioGroup.addView(wednesdayRadioButton); 
    radioGroup.addView(thursdayRadioButton); 
    radioGroup.addView(fridayRadioButton); 
    CheckBox checkBox = new CheckBox(this); 
    ScrollView scrollView = new ScrollView(this); 
    mainLinear.addView(scrollView); 
    LinearLayout deleteAppointmentsLayout = new LinearLayout(this); 
    deleteAppointmentsLayout.setOrientation(LinearLayout.VERTICAL); 
    scrollView.addView(deleteAppointmentsLayout); 
    APData = new AppointmentDataSource(this); 
    APData.open(); 
    //printf("Go to here"); 
    List <Appointment> appointments = APData.retrieveAllAppointments(); 
    APData.close(); 
    String time, duration, description, boxText; 
    long id; 
    int loop = 0; 
    if (mondayRadioButton.isChecked()) { 
    deleteAppointmentsLayout.removeAllViews(); 
    for (Iterator <Appointment> i = appointments.iterator(); i.hasNext();) { 
     Appointment item = i.next(); 
     if (item.getDay() == 1) { 
     System.out.println("fucken did work"); 
     id = item.getId(); 
     time = item.getTime(); 
     duration = item.getDuration(); 
     description = item.getDescription(); 
     boxText = time + ", " + duration + ", " + description; 
     checkBox.setText(boxText); 
     checkBox.setId((int) id); 
     deleteAppointmentsLayout.addView(checkBox); 
     } else { 
     System.out.println("fucken didnt work"); 
     } 
    } 
    } 
    if (tuesdayRadioButton.isChecked()) { 
    deleteAppointmentsLayout.removeAllViews(); 
    for (Iterator <Appointment> i = appointments.iterator(); i.hasNext();) { 
     Appointment item = i.next(); 
     if (item.getDay() == 2) { 
     id = item.getId(); 
     time = item.getTime(); 
     duration = item.getDuration(); 
     description = item.getDescription(); 
     boxText = time + ", " + duration + ", " + description; 
     checkBox.setText(boxText); 
     checkBox.setId((int) id); 
     deleteAppointmentsLayout.addView(checkBox); 
     } else {} 
    } 
    } 
    if (wednesdayRadioButton.isChecked()) { 
    deleteAppointmentsLayout.removeAllViews(); 
    for (Iterator <Appointment> i = appointments.iterator(); i.hasNext();) { 
     Appointment item = i.next(); 
     if (item.getDay() == 3) { 
     id = item.getId(); 
     time = item.getTime(); 
     duration = item.getDuration(); 
     description = item.getDescription(); 
     boxText = time + ", " + duration + ", " + description; 
     checkBox.setText(boxText); 
     checkBox.setId((int) id); 
     deleteAppointmentsLayout.addView(checkBox); 
     } else {} 
    } 
    } 
    if (thursdayRadioButton.isChecked()) { 
    deleteAppointmentsLayout.removeAllViews(); 
    for (Iterator <Appointment> i = appointments.iterator(); i.hasNext();) { 
     Appointment item = i.next(); 
     if (item.getDay() == 4) { 
     id = item.getId(); 
     time = item.getTime(); 
     duration = item.getDuration(); 
     description = item.getDescription(); 
     boxText = time + ", " + duration + ", " + description; 
     checkBox.setText(boxText); 
     checkBox.setId((int) id); 
     deleteAppointmentsLayout.addView(checkBox); 
     } else {} 
    } 
    } 
    if (fridayRadioButton.isChecked()) { 
    deleteAppointmentsLayout.removeAllViews(); 
    for (Iterator <Appointment> i = appointments.iterator(); i.hasNext();) { 
     Appointment item = i.next(); 
     if (item.getDay() == 5) { 
     id = item.getId(); 
     time = item.getTime(); 
     duration = item.getDuration(); 
     description = item.getDescription(); 
     boxText = time + ", " + duration + ", " + description; 
     checkBox.setText(boxText); 
     checkBox.setId((int) id); 
     deleteAppointmentsLayout.addView(checkBox); 
     } else {} 
    } 
    } 
    this.setContentView(mainLinear); 
    deleteSelectedButton.setOnClickListener(new View.OnClickListener() {@ 
    Override 
    public void onClick(View view) {} 
    }); 
    backButton.setOnClickListener(new View.OnClickListener() {@ 
    Override 
    public void onClick(View view) { 
     finish(); 
    } 
    }); 
} 

обновленный код (хочет, чтобы изменить все переменный FINAL и в результате описания продолжительности времени и boxtext ошибки с «Конечной локальной переменной описание не может быть назначена, так как определены в типе ограждающей»< - только делает, что, когда я сделать CheckBox окончательный Aswell)

mondayRadioButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 

       if(mondayRadioButton.isChecked()){ 
       deleteAppointmentsLayout.removeAllViews(); 
      for(Iterator<Appointment> i = appointments.iterator(); i.hasNext();){ 
       Appointment item = i.next(); 
        if(item.getDay() == 1){ 
         System.out.println("fucken did work"); 
         id = item.getId(); 
         time = item.getTime(); 
         duration = item.getDuration(); 
         description = item.getDescription(); 
         boxText = time + ", " + duration + ", " + description; 
         checkBox.setText(boxText); 
         checkBox.setId((int) id); 
         deleteAppointmentsLayout.addView(checkBox); 

        } 
        else { 
         System.out.println("fucken didnt work"); 
        } 
      } 
      } 
      } 

     }); 
+0

Это очень много кода для просеивания для небольшой проблемы. Разум разрезал его только на соответствующие биты? – Zyerah

ответ

0

вы должны написать код выше в OnCreate, он будет работать в первый раз, когда вы входите в экран, позже не будет, так что вы n ПЕД Выполнить код выше, когда событие вызывает так

Для отдельных переключателей, установленных onClickLister

radiobutton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 

        //your code here 
      } 

     }); 

И для группы setOnCheckedChangeListener как этот

grp.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

      public void onCheckedChanged(RadioGroup arg0, int arg1) { 
        //your code here 

      } 
     }); 

почтовый индекс внутри вышеуказанных слушателей

Вы также можете использовать onCheckChangeListener на радиообъективе

radiobtn.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

      public void onCheckedChanged(CompoundButton arg0, boolean arg1) { 
       // your code here 

      } 
     }); 

Edit:

public class MainActivity extends Activity { 

    EditText message, password, username; // these are called fields 
    Context context; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

//instantiate like this 
     username = new EditText(this); 
     password = (EditText) findViewById(R.id.editText2); 
     message = (EditText) findViewById(R.id.editText3); 
} 
} 
+0

Когда я использую метод Group "radioGroup.setOnCheckedChangeListener (новый OnCheckedChangeListener() {и поместите код if внутри, он просто кажется, что все ошибки. – user2253722

+0

@ user2253722 Опубликовать только релевантный код, который необходимо выполнить, когда установлен переключатель. я вижу ваш обновленный код, опубликую его – Pragnani

+0

обновленный оригинальный пост – user2253722

0

Вы могли бы попытаться реализовать "onCheckedChanged()" на RadioGroup, то обновление информации в макете, или даже надувать другой макет на основе проверенного радио.

Смежные вопросы