3

我创建了 2 个类和一个接口。一个处理对话框点击的接口,一个包含一个按钮和一个 textView 的 MainActivity 类。MainActiviy 类实例化了我的第二个类(FireMissilesFragment),其中包含一个 AlertDialog 作为片段。在 FireMisslesFragment 中,我动态创建了 EditText。我的应用程序的问题是,当我在实例化 FireMissilesFragment 的 mainActivity 类中调用 (onsavenstancestate) 时,我尝试保存我的 editText 值,以便当弹出窗口关闭并重新启动它时,editText 的值将保持它的值一旦弹出窗口再次打开。

我已经尝试过(onSaveInstanceState)方法并且值保持不变;但是,一旦再次启动对话框,我仍有可能重新创建被破坏的内容。有人可以解释一下这个问题。

这是我的代码:

//================================接口================ ======================//

        public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog,EditText[] editText);
public void onDialogNegativeClick(DialogFragment dialog);
     }

//===========================MainActivity 类==================== =========//

    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;


          public class MainActivity extends FragmentActivity implements   `               NoticeDialogListener{ 

     private  EditText[] _edText;
     private TextView _tv;

     private Multiplication multi;
     private Double[] s;
     private String s1;
     public static final String _SCORE1 = "score1";
     public static final String _SCORE2 = "score2";


     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         setContentView(R.layout.activity_main);
                _tv = (TextView)findViewById(R.id.textView1);
               Button dAction = (Button)findViewById(R.id.button1);

                  s = new Double[2];


             dAction.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {//open();
        confirmFireMissiles();


        }

              });//ssetOnclickLi...
    ///success thank god.

            //===================================================//


              }
      public void confirmFireMissiles() {

    DialogFragment newFragment = new FireMissilesDialogFragment();
    newFragment.show(getSupportFragmentManager(),"ff");

         }//confirmFireMisslesClosing brace

         // The below is what happens when the Button "multiply" in 
             Dialog window pops up.
@Override
public void onDialogPositiveClick(DialogFragment dialog,EditText[] 
                     editText) {    


    _edText = editText; // is this association

         multi = new Multiplication();
       try{ 
      // gets the text and stores to string array.

          s[0]=Double.parseDouble(_edText[0].getText().toString());
     s[1]=Double.parseDouble(_edText[0].getText().toString());
     Log.d("hello", String.valueOf(s[0]));


    }catch(NumberFormatException e){
              _tv.setText("please Insert an Number and calculate  again"); // 
        Log.d("Error", "place in numbers please");
    } 
        s1 = String.valueOf(multi.multiply(s[0],s[1]));
        //set Textview to s1.
                 _tv.setText(s1);
             }
@Override
public void onDialogNegativeClick(DialogFragment dialog) {}

}

//================================================= =================================// public class FireMissilesDialogFragment extends DialogFragment { private AlertDialog.Builder builder; 私人 EditText[] _edText; // 准备就绪时启用 private NoticeDialogListener _mListener; 公共静态最终字符串_SCORE1 =“score1”;公共静态最终字符串_SCORE2 =“score2”;私人 Double[] s;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        builder = new AlertDialog.Builder(getActivity());
           //shows added content to dialog.
     //  d = new String[2];
             s = new Double[2];




    if(savedInstanceState !=null){


   s[0] =  Double.parseDouble(savedInstanceState.getString(_SCORE1));
  s[1] = Double.parseDouble(savedInstanceState.getString(_SCORE2));
       Log.d("Hey",String.valueOf(s[0]));

     _edText[0].setText(String.valueOf(s[0]));
        showIt();



    }else{
         showIt();

    }
          //sets the characterisitcs of  the dialogue.
        builder.setTitle("We are all stars of the show.");
        builder.setMessage( "we are strong")

             .setPositiveButton("Multiply", new  
               DialogInterface.OnClickListener(){
         public void onClick(DialogInterface dialog, int id) {

                    // enable when ready


   _mListener.onDialogPositiveClick(FireMissilesDialogFragment.this,_edText); 

                   }
               });

        // Create the AlertDialog object and return it

             return builder.create();
    }

 public  void showIt(){

// 这段代码创建了一个线性布局,假设显示在对话框弹出窗口中。LayoutParams 参数 = new
LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f); 线性布局布局=新线性布局(getActivity());layout.setLayoutParams(param); layout.setOrientation(LinearLayout.VERTICAL); layout.setBackgroundColor(Color.BLACK);

          // Dynamically place EditText efficiently Inside Linear Layout.
          _edText = new EditText[4];
           for (int i = 0;i< _edText.length;i++) {

         _edText[i] = new EditText(getActivity());
         _edText[i].setInputType(InputType.TYPE_CLASS_NUMBER | 
              InputType.TYPE_NUMBER_FLAG_DECIMAL); 
         _edText[i].setTextSize(20)
        try{
         s[i] =Double.parseDouble(   
                                  _edText[i].getText().toString());
        }catch(NumberFormatException e){
        //  Log.d("hello", "wrong input");
        }
         layout.addView(_edText[i]);
            }
         builder.setView(layout);
            }
   //============================================== Look over this code======////////////
   @Override
    public void onAttach(Activity activity) {
       super.onAttach(activity);
         //Verify that the host activity implements the callback interface
        try {
          //   Instantiate the NoticeDialogListener so we can send events to the host
            _mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                   + " must implement NoticeDialogListener");
        }
    }


       @Override
   public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state

            savedInstanceState.putDouble(_SCORE1,s[0]);
        savedInstanceState.putDouble(_SCORE2,s[1]);
        super.onSaveInstanceState(savedInstanceState);
    }

}
4

1 回答 1

3

您可能可以SharedPreferences在那里使用和存储信息,然后将文本编辑的文本设置为共享首选项的结果?还是我把整个想法弄错了?

这是一个简单的保存功能的示例:

  SharedPrefrences scores = getSharedPreferences("key_name_here", Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = scores.edit();
  editor.putInt("key1", key1Var);
  editor.putInt("key2", key2Var);
  editor.commit();

并检索:

  Var = getPrefrences(Context.MODE_PRIVATE).getInt("key1",default value);

那应该可以解决问题

于 2013-06-20T21:48:51.023 回答