根据单击的按钮在 SharedPreferences 中保存变量 [英] Save variable in SharedPreferences based on which button is clicked
问题描述
我正在尝试为我的应用制定 EULA,但我们合作的不同国家/地区有不同的 EULA.
Im trying to make an EULA for my app, but there is a different EULA for the different countries we work with.
我的想法是我在 SharedPreferences 中保存一个字符串,例如南非的 ZA 和肯尼亚的 KE.因此,如果您单击南非按钮,它会将 SharedPreferences 中的字符串保存为 ZA,对于肯尼亚也是如此.单击按钮后,新活动将通过从 SharedPreferences 中拉出 ZA 或 KE 字符串来加载适当的 EULA.这就是我目前所拥有的:
my idea was that i save a String in SharedPreferences like ZA for South Africa and KE for Kenya. So if you click the South Africa button, it will save the string in SharedPreferences as ZA and the same for Kenya. Once the button has been clicked it the new activity will then load the appropriate EULA by pulling the ZA or KE string from the SharedPreferences. This is what i have at the moment:
Country_select.java
Country_select.java
public class country_select extends Activity {
private static final String TAG = "Logs";
public static final String PREFS_NAME = "PrefsFile";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_select);
final Button za_button = (Button) findViewById(R.id.btn_za);
Button ke_button = (Button) findViewById(R.id.btn_ke);
Log.i(TAG, "created buttons");
za_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "ZA");
editor.commit();
}
});
Log.i(TAG, "set button settings for ZA");
ke_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "KE");
editor.commit();
}
});
Log.i(TAG, "set button settings for KE");
}
我可能完全不正确,但布局文件上有 2 个按钮,一个用于 KE,一个用于 ZA.
I may have this totally incorrect but on the layout file there are 2 buttons, one for KE and one for ZA.
我想,当新活动加载时读取 SharedPreferences 是否有 ZA 或 KE?我在这里所做的是否正确?
I would like it, when the new activity is loaded to read SharedPreferences whether it has ZA or KE? Is what i have done here correct?
谢谢
推荐答案
我认为您最好使用 IntentExtras
,在您点击国家/地区按钮后的第一个活动中,将值存储在一个变量中当你想开始新的活动时,将数据作为额外的意图传递:
I think you're better off with using IntentExtras
, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
然后在新活动中,您可以像这样检索值:
And then inside the new activity you can retrieve the value like this:
String countryCode = getIntent().getExtras().getString("country");
这篇关于根据单击的按钮在 SharedPreferences 中保存变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!