我面臨的一個問題,而我在一個片段中使用此代碼,我做了一些你help..But的一些變化還是有一些錯誤..如何使用共享偏好片段活動
這是我想從正常活動中轉移到一個片段活性的代碼..
public class MainActivity extends Activity {
final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";
Button button;
EditText editText;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.userNameEditText);
button=(Button) findViewById(R.id.enterButton);
Log.d("DICTIONARY", "main activity started");
sharedPreferences=getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");
editText.setText(userNameString);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String string=editText.getText().toString();
Intent intent=new Intent(MainActivity.this, DictionaryListActivity.class);
intent.putExtra("user", string);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(USER_NAME_STRING, string);
editor.commit();
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
它示出錯誤等MODE_PRIVATE無法解析爲一個變量。所以我改變了Context.MODE_PRIVATE,然後它顯示「editText =(EditText)findViewById(R.id.userNameEditText);」行上無法訪問的代碼;
如何修復它?
THIS IS MY片段現在看起來喜歡:
public class FragmentA extends Fragment {
final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";
Button button;
EditText editText;
Context c;
SharedPreferences sharedPreferences;
public FragmentA() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
editText=(EditText) getView().findViewById(R.id.userNameEditText);
button=(Button) getView().findViewById(R.id.enterButton);
Log.d("DICTIONARY", "main activity started");
Context c =getActivity();
sharedPreferences=this.c.getSharedPreferences(SHARED_NAME_STRING,MODE_PRIVATE);
String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");
editText.setText(userNameString);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String string=editText.getText().toString();
Intent intent=new Intent("android.intent.action.JJJJ");
intent.putExtra("user", string);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(USER_NAME_STRING, string);
editor.commit();
startActivity(intent);
}
});
}
}
歡迎來到本SO社區。請閱讀SO鏈接http://stackoverflow.com/tour。您只需簡單閱讀就可以獲得聲望點。 –