从preferences.xml启动Activity并在onActivityResult中获取结果

Eli*_*oto 17 android android-preferences android-activity

这是对这个问题的补充.

我可以启动Activity但我也需要能够得到结果.我该怎么做?

我尝试在我的PreferencesActivity上覆盖onActivityResult无济于事.

我在偏好.xml中缺少一些额外的属性吗?

Kaa*_*rel 17

我所知道的最干净的解决方案是听取偏好的点击并明确启动意图.这种方式onActivityResult将照常调用.

假设您的意图偏好是用XML定义的,您可以像这样附加一个监听器(其中1234是请求代码onActivityResult):

Preference pref = (Preference) findPreference("prefKey");
pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
  @Override
  public boolean onPreferenceClick(Preference preference) {
    startActivityForResult(preference.getIntent(), 1234);
    return true;
  }
});
Run Code Online (Sandbox Code Playgroud)


Joe*_*Joe 14

尝试覆盖startActivity()您的PreferencesActivity类并startActivityForResult()在检查intent是我们感兴趣的那个之后调用它,类似于以下(使用1234作为请求代码):

public class PreferencesActivity {
    // ...

    @Override
    public void startActivity(Intent intent) {
        if (thisIsTheExpected(intent)) {
            super.startActivityForResult(intent, 1234);
        } else {
            super.startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int reqCode, int resCode, Intent data) {
        if (reqCode == 1234) {
            // should be getting called now
        }
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

根据您的需要,与OnPreferenceClickListener在代码中添加几个相比,这可能更简单:)


Maz*_*Zer 3

如果您想将数据从首选项活动传递到主要活动,请使用以下代码:

在您的主要活动课程(启动)中:

startActivityForResult(new Intent(main.this, preferences.class), 0);
Run Code Online (Sandbox Code Playgroud)

在您偏好的活动类别中(设置结果):

Intent i;
i.putStringExtra("name", "tom");
setResult(RESULT_OK, i);
finish();
Run Code Online (Sandbox Code Playgroud)

在您的主要活动课程中(获取结果):

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK){
            Log.d("test", data.getExtraString("name");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要添加任意数量的附加内容,不仅是字符串,还包括所有标准数据类型。

希望我做的一切都是正确的;)

编辑

正如卡雷尔告诉我的那样,我可能误解了这个问题。这是您从首选项活动中的主要活动接收数据的方法:

在您的主要活动中:启动首选项活动并附加数据

String foo = "hello";
Intent i = new Intent();
i.putExtra("testString", foo);//You can also add other types of variables here, see [1] for reference
i.setClass(main.this, preferences.class);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

在您的首选项活动中:接收附加到意图的数据

Bundle b = this.getIntent().getExtras();//[2]
if (b!=null){
    String recievedString = b.getString("testString");
    //The recievedString variable contains the String "hello" now, see [3]
}
Run Code Online (Sandbox Code Playgroud)

[1] https://developer.android.com/reference/android/content/Intent.html

[2] https://developer.android.com/reference/android/content/Intent.html#getExtras%28%29

[3] https://developer.android.com/reference/android/os/Bundle.html