gpt4 book ai didi

java - 根据单击的按钮将变量保存在 SharedPreferences 中

转载 作者:行者123 更新时间:2023-12-01 11:37:19 25 4
gpt4 key购买 nike

我正在尝试为我的应用制定 EULA,但与我们合作的不同国家/地区有不同的 EULA。

我的想法是在 SharedPreferences 中保存一个字符串,例如南非的 ZA 和肯尼亚的 KE。因此,如果您单击南非按钮,它会将 SharedPreferences 中的字符串保存为 ZA,肯尼亚也是如此。单击该按钮后,新 Activity 将通过从 SharedPreferences 中拉出 ZA 或 KE 字符串来加载适当的 EULA。这就是我现在所拥有的:

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。

我想,当新的activity加载时读取SharedPreferences是否有ZA或KE?我在这里所做的正确吗?

谢谢

最佳答案

我认为您最好使用 IntentExtras,在您的第一个 Activity 中,单击国家/地区按钮后,将值存储在变量中,当您想要启动新 Activity 时,将数据作为额外 Intent :

Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);

然后在新 Activity 中您可以检索如下值:

String countryCode = getIntent().getExtras().getString("country");

关于java - 根据单击的按钮将变量保存在 SharedPreferences 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29840045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com