如何从一个Fragment向另一个Fragment发送数据?

28

你好,我知道这个问题有答案。我已经尝试了所有的方法,但在我的应用中它没有起作用。 我正在开发一个包含3个片段活动的应用程序。第一个片段显示网站,第二个片段有列表视图,第三个片段另外有一个列表视图。现在,当用户点击列表项时,我想将URL从第三个片段发送到第一个片段。这是我所做的。

我正在从该片段向第一个片段发送字符串URL。

list.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position,
            long id) {
        FragmentC fragment = new  FragmentC();
        final Bundle bundle = new Bundle();
        bundle.putString("position", "http://www.facebook.com");            fragment.setArguments(bundle);}
});

这是第一个片段,我需要网址并希望在 Webview 中显示。

String url="http://www.hotelsearcher.net/";
        Bundle args = getArguments();
        if (args  != null){
        url = args.getString("position");
        }
        WebView webView= (WebView) V.findViewById(R.id.webView1);
        WebSettings webViewSettings = webView.getSettings();
        webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webViewSettings.setJavaScriptEnabled(true);
        webViewSettings.setPluginState(PluginState.ON);
        webView.loadUrl(url);

当我点击列表项时,我什么也没看到。它没有将我重定向到第一个片段。请帮帮我。

4个回答

93

使用 Bundle 发送 String

//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

在新的片段onCreateView中:

//Retrieve the value
String value = getArguments().getString("YourKey");

你的 YourNewFragment 是什么意思? - Muhidul Hassan
你的“Another fragment”是你想要接收字符串值的片段。 - João Marcos
2
容器指的是什么? - Muhidul Hassan
好的,它可以工作了。它重定向到第一个片段。但是它正在显示对话框来选择浏览器以查看网站,而不是在我的webview上显示网站。你能帮我吗?我会接受这个答案的 :) - Muhidul Hassan
请关闭此问题并打开另一个新问题。我会在新问题中帮助您。 - João Marcos
显示剩余8条评论

5

1. 如果多个片段由同一活动托管- 您不能将Intent强制转换为Fragment。 Fragment是Activity的一部分,它本身不是一个Activity。因此,要在片段之间共享字符串,您可以在Activity中声明静态字符串。从片段A访问该字符串以设置值并在片段B中获取字符串值。

2. 两个片段由不同的活动托管- 然后您可以使用putExtra将来自Activity A的Fragment A的字符串传递到Activity B。在Activity B中存储该字符串并在Fragment B中使用它。


我有不同的Fragment,我想从一个Fragment向另一个Fragment发送字符串。 - Muhidul Hassan
是的,明白了,但这两个片段都由同一个活动托管吗? - ViJay

2
你需要将你的 Bundle 附加到你的 Fragment 上。
fragment.setArguments(bundle);

然后更改或替换新片段。

你必须确保字符串在新片段中。调试!!


0

您可以通过两种方式发送数据。第一种是在发送数据时启动该片段。

SecondFragment ldf = new SecondFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

其次,当您想要在不打开片段的情况下发送数据时

FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.add(R.id.fragContainer1, new ModelListFragment(), FRAG_MODEL_LIST);
ft.add(R.id.fragContainer2, new TrimListFragment(), FRAG_TRIM_LIST);
ft.commit();

Fragment fragment = mFragmentManager.findFragmentByTag(MainActivity.FRAG_MODEL_LIST);
Log.d("MY", "found fragment: " + (fragment != null));

我该如何在第二个片段中接收数据? - Fletchy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接