我想在主要活动中使用作为 ip 的 edittext 首选项的新值。我不必在主要活动中显示价值。当我尝试这样做时,我只会获得默认值,直到我关闭并再次打开应用程序。
我只知道如何在写入后保存新值。
这是主要活动的代码
public String IP;
public int puerto;
//Para crear el menu de settings
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
//Se ponen las opciones de los iconos del menu
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
break;
case R.id.camera:
break;
case R.id.exit:
this.finish();
break;
default:
break;
}
return true;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
IP = preferences.getString("prefIP", "127.0.0.1");
puerto = Integer.parseInt(preferences.getString("prefPort", "1101"));
//After that I use the values to use a socket connection
}
//偏好活动代码
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}