简体   繁体   中英

preserve edittext data when navigation back button pressed in android

在我的申请表中有几个编辑文本,其中导航回按我的数据丢失并且焦点没有我可以在单击导航键后退按钮后保留该数据如何解决这个问题

welcome to posting on StackOverflow. Usually it's good practice to post what you've tried, instead of fix this for me questions, but since you're new here I'll give you the info you'll need.

When pressing the hardware back button onBackPressed is triggered, you'll need to override it like this:

@Override
public void onBackPressed() {
}

Then you'll need to set the activity result like this:

Intent resultIntent = new Intent();
resultIntent.putExtra("edit_text_info", editText.getText().toString()); 
setResult(Activity.RESULT_OK, resultIntent);
finish();

And start this activity for result:

startActivityForResult(Activity, ActivityRequestCode);

Then override the onresult of the activity calling the activity with the edittext

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ActivityRequestCode && resultCode == RESULT_OK && data != null) {
        editText = data.getStringExtra(ActivityRequestCode);
    }
}

After receiving the state from the activity with the editText keep it in a variable and return it once you navigate back to it with putStringExtra and... done.

An other solution is to create a fragment containing this edittext and keep the state in the activity, but my assumptions are that you're new to Android so this is probably easier (and of course better then defining a Singleton or something).

I got answer for this.In custom edittext which is used in custom list view,we have to save when every character is changed.

edittext.addTextChangedListener(new TextWatcher() {
       @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {
       }
       @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {            
       }
       @Override
       public void afterTextChanged(Editable s) {
                String value =s.toString();
                mInterface.valueChanged((int)getTag(),value);
       }
});

This is value storing method

@Override
public void valueChanged(int position, String value) {
    EachField eachfld =(EachField) eachFields.get(position);
    obtDetails.put(eachfld.key,value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM