我不了解如何在两个片段之间传输数据。我试过这个:
public class Connection extends Fragment
{
SendMessage sender;
public interface SendMessage
{
public void send(String one, String two);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//my data
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
send = (SendMessage) getActivity();
}
private class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(final Context context, Intent intent)
{
if(message.equals("POS"))
{
sender.send(position,id);
}
}
}
在第一个片段中;在MainActivity中:
public class MainActivity extends FragmentActivity implements Connection.SendMessage
{
protected void onCreate(Bundle savedInstanceState)
{
//my code
}
@Override
public void send(String one, String two)
{
Map map = new Map();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
}
}
并在Map片段中(它需要接收此数据):
public class Map extends Fragment
{
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle bundle = new Bundle();
bundle.getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID");
}
//then show this on googleMaps
}
}
但我不明白为什么这段代码不起作用。你能帮助我吗?感谢...
答案 0 :(得分:2)
1)请将您的类名从Map.java更改为其他任何内容。因为在java中将map导入为java.util Package。
2)
Fragment map = new Fragment ();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
map.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, map).commit();
并收到
Bundle bundle = getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID:"); (You miss : in ID)
}
答案 1 :(得分:0)
执行此发送片段
String cid=id.getText().toString();
Fragment fr=new friendfragment();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("CID", cid);
fr.setArguments(args);
ft.commit();
收到片段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("CID");
return inflater.inflate(R.layout.fragment, container, false);
}
答案 2 :(得分:0)
嗯,首先。您的接收片段实际上正在访问一个空包。你这样做:
Bundle bundle = new Bundle();
bundle.getArguments();
而不是:
Bundle bundle = getArguments();
其次,两个片段之间通信的好方法是使用接口。界面使用第二个片段与活动和活动进行通信。 这是谷歌的教程:
http://developer.android.com/training/basics/fragments/communicating.html
此外,您似乎没有为Map Fragment夸大任何xml布局文件,甚至在创建它之后将其与FragmentTransaction一起添加。这是一个简短而又甜蜜的教程:
http://android-er.blogspot.com/2011/12/programmatically-add-fragment.html