2012-07-28 2 views
1

У меня проблема с радиообменами, потому что, когда я удаляю экземпляр со сцены, где находятся радиокнопки, если я снова создам экземпляр, то радиокнопки сохраняют последний выбор.Quiz app + singleton classes as3

(я написал класс на испанском языке, если у Вас есть проблемы, чтобы определить концепцию, пожалуйста, спросите меня)

класса (crearPregunta.as или askQuestion.as)

package src.com.akkadian 

{

import fl.controls.RadioButtonGroup; 
import flash.display.DisplayObject; 
import flash.display.MovieClip; 
import flash.events.*; 
import flash.events.MouseEvent; 
import flash.net.*; 
import flash.text.*; 
import flash.utils.Timer; 
import flash.xml.*; 
import src.com.akkadian.manipularXML; 

public class crearPregunta extends MovieClip 
{ 

    private static var _instance:crearPregunta = null; 

    private var xmlPath:String; 
    private var radioGroup1:RadioButtonGroup = new RadioButtonGroup("Questions"); 
    private var xmlLoader:URLLoader = new URLLoader(); 
    private var instanciaXML:manipularXML; 
    protected var time:Timer; 
    private var rs:String; 
    private var resp:XMLList; 
    private var re:XMLList; 
    private var pre:XMLList; 
    private var opSeleccionada:Number; 
    private var resultado:Boolean = false; 

    public function crearPregunta() 
    { 


    } 

    public static function getInstance():crearPregunta 
    { 

     if (_instance == null) 
     { 

      _instance = new crearPregunta(); 

     } 

     return _instance; 
    } 

    private function generarContenido() 
    { 

     // Crea the XML instance from manipularXML class 
     this.instanciaXML = manipularXML.generarInstancia(); 

     // Send the path of the file 
     this.xmlPath = "src/com/akkadian/preguntas.xml"; 

     // Add the listener to proceed when the load is finished   
     xmlLoader.addEventListener(Event.COMPLETE, inXML); 
     xmlLoader.load(new URLRequest(this.xmlPath)); 

     // adding a listener to the button sendResponse 
     enviarRespuesta.addEventListener(MouseEvent.CLICK, recibirRespuesta); 
     enviarRespuesta.buttonMode = true; 

    } 

    public function validarRespuesta(opcionSeleccionada:String):Boolean 
    { 
     // Option chosen 
     opSeleccionada = Number(opcionSeleccionada); 

     // Generate the content 
     generarContenido(); 

     // Send the result 
     return resultado; 
    } 

    private function inXML(e:Event):void 
    { 
     // Add the radiobuttons to an Array 
     var radios:Array = [casoA, casoB, casoC]; 

     // Obtain the data from the XML 
     var data = instanciaXML.obtenerInfo(e.target.data); 


     for each (var nodo:XML in data.pregunta) 
     { 

      if ([email protected] == opSeleccionada) 
      { 
       // Keep the answer for the option chosen 
       resp = data.pregunta[opSeleccionada - 1].respuesta; 

       // Keep the value for the option chosen 
       re = data.pregunta[opSeleccionada - 1][email protected]; 

       // Keep the question 
       pre = data.pregunta[opSeleccionada - 1][email protected] 

       // add the value of the question to the dinamic textfield 
       question.text = pre; 

       for (var u:uint = 0; u < radios.length; u++) 
       { 

        radios[u].group = radioGroup1; 
        radios[u].textField.multiline = true; 
        radios[u].textField.wordWrap = true; 
        radios[u].textField.width = 230; 
        radios[u].textField.height = 100; 
        radios[u].textField.autoSize = TextFieldAutoSize.LEFT; 


        // Add the answers to the labels 
        radios[u].label = resp[u]; 

        // Add the answers to the values 
        radios[u].value = re[u]; 

       } 

      } 

     } 
    } 

    private function recibirRespuesta(m:MouseEvent) 
    { 

     for each (var tre:XML in re) 
     { 
      // if the value of the answer is equal to the value stored 
      if (this.radioGroup1.selection.value == re) 
      { 
       // Save the result as true 
       this.resultado = true; 

       // Add the value of the answer to the textfield included on this Instance 
       result_txt.text = "Correcto"; 
      } 
      else 
      { 
       // Save the result as false 
       this.resultado = false; 

       // Add the value of the answer to the textfield included on this Instance 
       result_txt.text = "Incorrecto"; 
      } 
     } 

     // Add a function to create a timer 
     agregarTimer(); 

    } 

    private function agregarTimer() 
    { 
     // Setup the timer 
     time = new Timer(1000, 1); 
     time.addEventListener(TimerEvent.TIMER_COMPLETE, cerrarTimer); 
     time.start(); 

    } 

    private function cerrarTimer(t:TimerEvent) 
    { 
     // Just for information, I verify which are the instances that at present ran in the Main instance 
     Main.Instancia.obtenerNombreHijos(); 

     // Remove the instance askQuestion from the Main 
     Main.Instancia.removeChildAt(2); 

     // I certify that the instance is deleted 
     Main.Instancia.obtenerNombreHijos(); 

     // I change the instance of the xml class to null 
     instanciaXML = null; 


    } 

} 

}

Результат: Что происходит сейчас?

  1. Пользователь запустить пустяки: первый, выберите вариант запуска (сетка опций создается)
  2. пользователь может выбрать один из вариантов (экземпляр askQuestion создается)
  3. Когда пользователь выбирает опцию из в радиокнопки (результат отображается на result_txt.text)
  4. таймер исполненные
  5. Удалите экземпляр (askQuestion) из главного класса
  6. IF пользователю выбрать другой вариант, вопрос и ап swers отображаются корректно, но в радиоблоке сохраняется опция, выбранная ранее, и результат result_txt.text показывает результат этого выбора. Это неправильно, потому что выбор не требуется.

Я другая ситуация от этого .. Я это:. статический экземпляр а (здесь создается экземпляр с) статический экземпляр б (здесь результат работы этого экземпляра будет удален, когда будет получен результат) экземпляр с (результат отображения) Как я могу сделать, чтобы передать информацию от экземпляра б к примеру Ĉ инф экземпляр был создан в экземпляр

ответ

0

Я считаю, что проблема заключается в том, что вы повторно используете одну и ту же группу переключателей каждый раз, но вы не сбрасываете selectedIndex или selectedValue этой группы переключателей. Я считаю, что это исправит проблему:

  radioGroup1.selectedIndex=-1; 
      for (var u:uint = 0; u < radios.length; u++) 
      { 

       radios[u].group = radioGroup1; 
       radios[u].textField.multiline = true; 
       radios[u].textField.wordWrap = true; 
       radios[u].textField.width = 230; 
       radios[u].textField.height = 100; 
       radios[u].textField.autoSize = TextFieldAutoSize.LEFT; 


       // Add the answers to the labels 
       radios[u].label = resp[u]; 

       // Add the answers to the values 
       radios[u].value = re[u]; 

      } 
+0

У меня есть другая ситуация из этого .. У меня есть: static instance a (здесь создается экземпляр c) статический экземпляр b (здесь результат операции. Этот экземпляр будет удален, когда будет получен результат) instance c (результат отображается) Как я могу сделать, чтобы отправить информацию из экземпляра b в экземпляр c inf, экземпляр был создан в примере a – m4g4bu

+0

Если это устраняет исходную проблему с переключателем повторный выбор, вы должны принять его и опубликовать новую проблему, поскольку это собственный вопрос. Цель SO заключается не в том, чтобы люди могли помочь вам завершить свой проект, цель состоит в том, чтобы иметь хранилище вопросов и ответов, которые могут принести пользу всем. Если вещи не сохраняются по частям, они не так полезны. – shaunhusain

+0

Да, моя ошибка (y) – m4g4bu

1

чтобы удалить что-нибудь в Flash, или, другими словами, готовить его для мусора C ollector попробуйте удалить всех слушателей из объекта, удалив его со сцены, а затем установив для него значение null.