Android如何在按钮单击时将文本从编辑文本保存到共享首选项

时间:2014-02-20 10:26:10

标签: android sharedpreferences android-edittext

我可以在编辑文本上输入文本或从微调器中选择一个预定义的文本。如果我从微调器中选择,我只在编辑文本上显示它。我想如果单击“保存”按钮,“编辑文本”中的文本将保存到“共享首选项”。现在,我将文本保存在onAfterTextChanged()上,但我希望按下按钮保存。请建议。我甚至按照教程,但没有得到太多。

MainActivity.java


    private EditText message;
    Spinner spinner;
    Button save;
      @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(this);
    save = (Button) findViewById(R.id.save);
    save.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            pref.edit().putString("autoSave", message.getText().toString()).commit();     
        }
    }) ;



    message = (EditText) findViewById(R.id.et_message);
    // message.setFocusable(false);

    spinner = (Spinner) findViewById(R.id.Spin_alert_message);
    dbHelper = new MySQLiteHelper(MainActivity.this);
    selectedContactList = dbHelper.getAllContacts();
    ArrayAdapter<String> adp = new ArrayAdapter<String>(
            getApplicationContext(), android.R.layout.simple_spinner_item,
            alert);
    spinner.setAdapter(adp);

    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int position, long id) {
            // message.setSelection(pref.getString("AutoSave",""));
            String selectedItem = alert[position];
            message.setText(selectedItem);

            // loads the text that has been stored to SP and set it to
            // EditText

            // to bring cursor to front
            message.setSelection(message.getText().length());



        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    /************************** saving custom message *****************************/





    ListView contactlist = (ListView) findViewById(R.id.contactListitems);
    Resources res = getResources();
    adapter = new CustomAdapter(MainActivity.this, selectedContactList,
            res, MainActivity.this);
    contactlist.setAdapter(adapter);

3 个答案:

答案 0 :(得分:1)

将此添加到onCreate

save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
        pref.edit().putString("autoSave", message.getText().toString()).commit();     
    }
});

另请注意,您正在拨打多个电话:

final SharedPreferences pref = PreferenceManager
                        .getDefaultSharedPreferences(this);

final SharedPreferences preferences = PreferenceManager
                        .getDefaultSharedPreferences(this);

做同样的事情,那么为什么不重用pref变量而不是创建对同一SharedPreferences的新引用?

答案 1 :(得分:1)

这样做......

    private EditText message;
        Spinner spinner;
        Button save;
          @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);

                    save = (Button) findViewById(R.id.save);
                    save.setOnClickListener(onAddLocationButtonPressed) ;



                    message = (EditText) findViewById(R.id.et_message);
                    // message.setFocusable(false);

                    spinner = (Spinner) findViewById(R.id.Spin_alert_message);

                    selectedContactList = dbHelper.getAllContacts();
                    ArrayAdapter<String> adp = new ArrayAdapter<String>(
                            getApplicationContext(), android.R.layout.simple_spinner_item,
                            alert);
                    spinner.setAdapter(adp);
                    final SharedPreferences pref = PreferenceManager
                            .getDefaultSharedPreferences(this);
                    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                int position, long id) {
                            // message.setSelection(pref.getString("AutoSave",""));
                            String selectedItem = alert[position];
                            message.setText(selectedItem);

                            // loads the text that has been stored to SP and set it to
                            // EditText
                            message.setText(pref.getString("Entered", ""));
                            // to bring cursor to front
                            message.setSelection(message.getText().length());

                            message.addTextChangedListener(new TextWatcher() {

                                @Override
                                public void onTextChanged(CharSequence s, int start,
                                        int before, int count) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void beforeTextChanged(CharSequence s, int start,
                                        int count, int after) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void afterTextChanged(Editable s) {
                                    // TODO Auto-generated method stub
                                    // saving text after it is changed by the user
                                    pref.edit().putString("Entered", s.toString()).commit();


                                }
                            });

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                        }
                    });

                    /************************** saving custom message *****************************/

                    // for saving text that user can change as per need
                    final SharedPreferences preferences = PreferenceManager
                            .getDefaultSharedPreferences(this);

                    // loads the text that has been stored to SP and set it to Edit Text
                    message.setText(preferences.getString("autoSave", ""));

                    // adding addTextChangedListner() to the Edit Text View
                    message.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before,
                                int count) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count,
                                int after) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            // TODO Auto-generated method stub
                            // saving text after it is changed by the user
                            preferences.edit().putString("autoSave", s.toString()).commit();

                    });
                    ListView contactlist = (ListView) findViewById(R.id.contactListitems);
                    Resources res = getResources();
                    adapter = new CustomAdapter(MainActivity.this, selectedContactList,
                            res, MainActivity.this);
                    contactlist.setAdapter(adapter);
            }   

        private View.OnClickListener onAddLocationButtonPressed = new View.OnClickListener() {

                public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                            Editor editor = preferences.edit();

     editor.putString("autoSave", message.getText().toString()).commit();

                }
            };

答案 2 :(得分:1)

on Button点击此处:

private OnClickListener onsaveButtonClick = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        ReturningClass.setMY_NAME_PREF(getApplicationContext(), "Amresh");
        ReturningClass.setMY_USERID_PREF(getApplicationContext(), "8");


    }
};

ReturningClass.java

public class ReturningClass {

    private static String MY_NAME_PREF = "mystringpref";

    private static String MY_USERID_PREF = "shareduserid";

    public static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences("UserNameAcrossApplication",
                context.MODE_PRIVATE);

    }

    public static String getMY_NAME_PREF(Context context) {
        return getPrefs(context).getString(MY_NAME_PREF, "");
    }

    public static void setMY_NAME_PREF(Context context, String value) {
        getPrefs(context).edit().putString(MY_NAME_PREF, value).commit();
    }

    public static String getMY_USERID_PREF(Context context) {
        return getPrefs(context).getString(MY_USERID_PREF, "");
    }

    public static void setMY_USERID_PREF(Context context, String value) {
        getPrefs(context).edit().putString(MY_USERID_PREF, value).commit();
    }

}

你可以得到这样的值:

String Name = ReturningClass.getMY_NAME_PREF(MainActivity.this);
String Id = ReturningClass.getMY_USERID_PREF(MainActivity.this);

使用此代码,您可以在任何Activity中获取或存储值。