编辑时,应用程序中的“编辑”按钮不会保存

时间:2018-02-27 17:49:58

标签: android

我可以编辑Android Studio中我的应用的EditButton,但是一旦您编辑了文本,当您退出窗口时它将无法保存。该怎么办?

 public class BellPepperActivity extends AppCompatActivity {

    TextView bpTextView;
    AlertDialog dialog;
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bell_pepper);

        bpTextView = (TextView) findViewById(R.id.bpTextView);
        dialog = new AlertDialog.Builder(this).create();
        editText = new  EditText(this);
        dialog.setTitle("BELL PEPPER");

        dialog.setView(editText);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "SAVE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                bpTextView.setText(editText.getText());
            }
        });

        bpTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText(bpTextView.getText());
                dialog.show();
            }
        });


    }
}

1 个答案:

答案 0 :(得分:0)

通过窗口,我假设你是Activity(你创建的AppCompatActivity)。要维护活动中的状态,您必须了解activity lifecycle。基本上当你离开时,你必须保存实例状态:

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString(TEXT_VIEW_KEY, editText.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}

当您恢复状态时,您也会这样做:

//只有先前使用保存的实例保存时,才会调用此回调 // onSaveInstanceState()。我们在onCreate()中恢复某些状态,同时我们可以选择恢复

// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    editText.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}

显然你必须在班级顶部创建一个TEXT_VIEW_KEY作为私人最终字符串:

private static final String TEXT_VIEW_KEY = "TEXT_VIEW_KEY";

未经测试,但现在应该适合你。有关更高级的生命周期处理,请了解Android Architecture Components,但这应该等到您了解Android应用程序中的基本活动生命周期。