我的要求:
我MainActivity
从其他应用程序接收数据。MainActivity
被列为shareable
。
现在,我需要将此数据传递给fragment
inMainActivity
并更新fragment's
textview
.
在MainActivity.java :这里我在handleSendText
方法中处理接收到的数据(这是一个 URL)。
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
}
}
}
在handleSendText
中,我正在尝试创建一个包并将该数据传递给我的片段。
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
Bundle bundle = new Bundle();
bundle.putString("url", sharedText);
// set Fragmentclass Arguments
AddTab fragobj = new AddTab(); //AddTab() is my Fragment class's name
fragobj.setArguments(bundle);
}
在Fragment 类中:在其 onCreateView()
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
//some code
Bundle bundle = this.getArguments();
if(bundle!=null) {
String sharedUrl = getArguments().getString("url");
textBox.setText(sharedUrl);
inflater.inflate(R.layout.fragment_add, container, false);
// to update the UI to reflect changes, I'm trying the
// above line. Is it right?
}
1)问题是控件永远不会到达if
循环内部,这意味着bundle
总是返回NULL
。
2)此外,如果我没有收到来自其他应用程序的数据。我想editText
留空,所以我必须执行此检查。我怎样才能做到这一点?
3)此外,从setArgument
的文档中,我了解到应该在片段附加到其活动之前调用它。那么如何在 Fragment 的 UI 中体现变化呢?
公共无效 setArguments(捆绑参数)
提供此片段的构造参数。这只能在片段附加到其活动之前调用;也就是说,您应该在构建片段后立即调用它。此处提供的参数将在片段销毁和创建过程中保留。