如何将数据从一个片段发送到另一个片段?

Muh*_*san 21 android android-webview android-listview android-fragments

嗨,我知道这个问题有答案.我已经尝试了所有这些,但它在我的应用程序中无效.我正在开发一个具有3个Fragment活动的应用程序.第一个片段显示一个网站,第二个片段显示listview,第三个片段显示另一个列表视图.现在我想在用户点击listitem时将第三个片段的URL发送到第一个片段.这就是我所做的.

我从这个Fragment发送字符串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);}
});
Run Code Online (Sandbox Code Playgroud)

这是我需要网址并希望在网页浏览中显示的第一个片段.

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);
Run Code Online (Sandbox Code Playgroud)

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

Joã*_*cos 76

使用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();
Run Code Online (Sandbox Code Playgroud)

onCreateView片段中:

//Retrieve the value
String value = getArguments().getString("YourKey");
Run Code Online (Sandbox Code Playgroud)

  • 容器是指什么? (2认同)
  • 什么容器? (2认同)

小智 5

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

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