我在FragmentActivity
进行服务调用,我需要将两个数据(名称和地址)分别传递给Fragment A和Fragment B.
这是我尝试的代码。
public class C extends FragmentActivity {
// public PassDataToFragments fragmentCommunicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.detail_pager);
serviceCall();
}
void serviceCall() {
JSONObject totalData = new JSONObject(result);
JSONObject jsonData = totalData.getJSONObject("result");
trainerStrName = jsonData.getString("name");
trainerStrAddress = jsonData.getString("address");
// activityCommunicator.passDataToFragment(trainerStrName); i am
// null pointer exception
// pass name to fragment A and address to fragment B
}
@Override
public SherlockFragment getItem(int arg0) {
switch (arg0) {
// Open Previous Projects
case 0:
FragmentA fragmentA = new FragmentA ();
return fragmentA;
// Open Certification
case 1:
FragmentB fragmentB = new FragmentB ();
return fragmentB;
}
return null;
}
}
我尝试的是我使用的界面,但我不知道如何使用并获取FragmentA的名称值和片段B的地址:
public interface PassDataToFragments {
public void passDataToFragment(String someValue);
}
class Fragment A extends Fragment implement PassDataToFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.trainers_certification,
container, false);
return view;
}
@Override
public void passDataToFragment(String someValue) {
//Log.e("string",someValue);
}
}
答案 0 :(得分:1)
传递来自此活动的数据
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("address", address);
FragmentA fragmentA = new FragmentA();
fragmentA.setArguments(bundle);
并在Fragment A onCreateView
方法中检索它:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
String name = getArguments().getString("name");
String address = getArguments().getString("address");
}
编辑
如果片段已经加载,那么你可以这样做(使用当前的实现)
像这样发送数据
PassDataToFragment fragA = (PassDataToFragment) getSupportFragmentManager().findFragmentById(R.id.container); // Change the id as per yours
fragA.passDataToFragment(name, address);
您将在片段A中的passDataToFragment()
中获取数据。
答案 1 :(得分:0)
您只需从片段中调用Activity的方法即可访问活动的数据:
获取片段中的值:
String name = ((C)getActivity()).getValue();
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT);
C班:
public String getValue()
{
return trainerStrDescription;
}
希望它有助于ツ