gpt4 book ai didi

java - 在 Android 上启动 Activity 并共享数据

转载 作者:行者123 更新时间:2023-12-01 09:27:05 24 4
gpt4 key购买 nike

我是 Android 编程新手,遇到了一个无法克服的问题。我使用 Android Studio 示例构建了一个 TabHost 应用程序。当用户按下按钮时,我想调用另一个打开设置页面的 Activity (我从 gui 创建了一个基本 Activity “MySettings”)。

问题 1:当 Activity 关闭时,MainActivity 重新运行 onCreate,所选选项卡返回到启动选项卡。有没有办法继续上次选择的选项卡?

调用代码为:

public void buttonPressed(View view) { 
Intent intent = new Intent(MainActivity.this,MySettings.class);
MainActivity.this.startActivity(intent);
}

问题 2:我无法在两个 Activity 之间共享数据:

主要 Activity :

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedpreferences.edit();

}

我的设置:

public class MySettings extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_inr);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);

sharedpreferences.edit().putInt("myvar",200);
sharedpreferences.edit().apply();
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();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
};

此代码运行,但当 MySettings Activity 关闭时,调用 Activity MainActivity 中的“myvar”不会更新。

public void setImage(){
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
int cvt=sharedpreferences.getInt("myvar",0);
}

最佳答案

问题 1:

您应该将选定的选项卡索引保存在您的 Activity 中,以便当它返回时,您可以在调用 onCreate 时读取该索引并选择它。

问题2:

@Luis Miguel Sierra 关于 SharedPreference 的说法是正确的。

但是您可能希望“startActivityForResult”将数据传递回第一个 Activity 。

Starting another activity doesn't have to be one-way. You can also start another activity and receive a result back. To receive a result, call startActivityForResult() (instead of startActivity()).

For example, your app can start a camera app and receive the captured photo as a result. Or, you might start the People app in order for the user to select a contact and you'll receive the contact details as a result.

Of course, the activity that responds must be designed to return a result. When it does, it sends the result as another Intent object. Your activity receives it in the onActivityResult() callback.

更多信息: Getting a Result from an Activity

关于java - 在 Android 上启动 Activity 并共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39750543/

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