访问EditText首选项对话框

时间:2016-04-28 22:33:02

标签: android dialog sharedpreferences edittextpreference

我很困惑我应该在哪里使用sharedPreferences放置此代码。我试图找出如何创建对话框。我想访问EditTextPreference对话框,一旦用户输入他们的名字,我想使用下面的代码将其保存到文件中

SharedPreferences mySharedPreferences = getSharedPreferences("MyData", 

      Context.MODE_PRIVATE);
      SharedPreferences.Editor editor  = mySharedPreferences.edit();

      editor.putString("user_name",userName.getText().toString());

      editor.commit();

这是我的主要活动

 public class MainActivity extends AppCompatActivity {

    EditText userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

       Button myButton = (Button) findViewById(R.id.show_button_id);
        myButton.setOnClickListener(new View.OnClickListener(){
            @Override
        public void onClick(View view){


            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent i = new Intent(MainActivity.this,UserPreferenceActivity.class);
            startActivity(i);
            //return true;
        }

        return super.onOptionsItemSelected(item);
     }
    }

这是我的UserPreferenceFragment java类

    public class UserPreferenceFragment extends PreferenceFragment {

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

        //LOAD THE PRFERENCE FROM AN XML RESOURCE FILE
      addPreferencesFromResource(R.xml.preferences);
    }//ends OnCreate




    }

这是我的UserPreferenceActivity java类

public class UserPreferenceActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
setContentView(R.layout.content_main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.
*/

getFragmentManager().beginTransaction()
.replace(android.R.id.content,new UserPreferenceFragment())
.commit();

}

这是我的首选项xml文件

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen     xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
    android:key="show_background_pic"
    android:title="@string/show_background_pic_title"
    android:summary="@string/show_background_pic_summary"
    android:defaultValue="true">

</CheckBoxPreference>

<EditTextPreference
    android:key="user_name"
    android:title="@string/user_acct_name_title"
    android:summary="@string/user_acct_name_summary"
    android:defaultValue="NONAME">


</EditTextPreference>

最后我的主要内容

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"

tools:showIn="@layout/activity_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/Shared_preferences_label"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/show_button_label"
    android:id="@+id/show_button_id"
    android:layout_below="@+id/textView"
    android:layout_alignParentStart="true" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

使用Preference类的setOnPreferenceChangeListener方法和Preference.OnPreferenceChangeListener接口。像这样的东西:

pref_general.xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">


    <EditTextPreference
        android:capitalize="words"
        android:defaultValue="@string/pref_default_display_name"
        android:inputType="textCapWords"
        android:key="@string/key_example_text"
        android:maxLines="1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="@string/pref_title_display_name" />
</PreferenceScreen>

SettingPreferenceFragment.java:

public class SettingPreferenceFragment extends PreferenceFragment {


    public final String TAG = "SettingActivity";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = super.onCreateView(inflater, container, savedInstanceState);
        addPreferencesFromResource(R.xml.pref_general);
        EditTextPreference location = (EditTextPreference) findPreference("example_text");
        location.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                String locstr = newValue.toString();
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("example_text", locstr);
                editor.commit();
                Log.e(TAG, "" + locstr);
                return true;
            }
        });

        return view;

    }
}