2016-08-24 55 views
0

嗨,所有人都可以告诉我在保存后,我在编辑文本中获得保存的数据,我的意思是当我保存一些文本,然后我希望该文本将始终出现在编辑文本谢谢。 这里是我的代码:我如何从共享首选项中检索编辑文本中的数据?

public class MainActivity extends AppCompatActivity { 

    private Toolbar toolbar; 
    private EditText inputName; 
    private TextInputLayout inputLayoutName; 
    private Button btnSave; 

    public static final String MyPREFERENCES = "MyPrefs" ; 
    public static final String Message = "nameKey"; 
    SharedPreferences sharedpreferences; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name); 
     inputName = (EditText) findViewById(R.id.input_message); 
     btnSave = (Button) findViewById(R.id.btn_save); 

     inputName.addTextChangedListener(new MyTextWatcher(inputName)); 
     sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 
     btnSave.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       String m = inputName.getText().toString(); 
       SharedPreferences.Editor editor = sharedpreferences.edit(); 

       editor.putString(Message, m); 
       editor.apply(); 
       Toast.makeText(getApplicationContext(), "Thank You!", Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 
+0

你能更清楚一点好吗?文本保留在EditText中,除非您明确从键盘上删除它。你的要求究竟是什么?您是否在活动之间切换,并希望文字在EditText中自动填充一次以进入相关活动? –

+0

'inputText.setText(sharedpreferences.getString(Message,“”));' – lionscribe

回答

2
inputName.setText(sharedpreferences.getString(Message, "default_value")); 
0

试试这个

btnSave.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        String m = inputName.getText().toString(); 
        SharedPreferences.Editor editor = sharedpreferences.edit(); 

        editor.putString(Message, m); 
        editor.apply(); 
        Toast.makeText(getApplicationContext(), "Thank You!", Toast.LENGTH_SHORT).show(); 
        inputName.setText(m, TextView.BufferType.EDITABLE); //set the text here 
       } 
      });