在ViewPager片段之间传递数据

时间:2013-10-04 03:46:54

标签: android android-fragments android-viewpager

要将值传递给我在ViewPager上的其他片段,我正在执行以下操作:

FragmentA.java

//Initial Declaration
ListPasser handler;


public interface ListPasser{
    public void onPodCastClick(int position, String url, String title, String body, String date);
}


//I am implementing a ListView inside the fragment
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Log.i(tag, mp3URL);
    Log.i(tag, String.valueOf(position));
    Log.i(tag, pod_title);
    Log.i(tag, pod_body);
    Log.i(tag, pod_date);
    handler.onPodCastClick(position, mp3URL, pod_title, pod_body, pod_date);

}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    try {
        handler = (ListPasser) getActivity();

    } catch (ClassCastException e) {
        Log.i(tag,"Activity " + getActivity().getClass().getSimpleName()
            + " does not implement the ElemetsListClickHandler interface");
        e.printStackTrace();
    }
}

MainActivity.java(ViewPager的实现类)

@Override
public void onPodCastClick(int position, String url, String title,
        String body, String date) {
    // TODO Auto-generated method stub
    Bundle element = new Bundle();
    element.putInt("position", position);
    element.putString("mp3url", url);
    element.putString("title", title);
    element.putString("body", body);
    element.putString("date", date);

    Fragment toGo = new FragmentB();
    toGo.setArguments(element);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.pager, toGo);
    transaction.commit();

}

FragmentB.java

TextView npTitle, npDate, npDescription;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.now_playing_layout, container, false);


    npTitle = (TextView)view.findViewById(R.id.npTitle);
    npDate = (TextView)view.findViewById(R.id.npDate);
    npDescription = (TextView)view.findViewById(R.id.npDescription);

    Bundle element = this.getArguments();
    if(element != null){
    String title = element.getString("title");
    String url = element.getString("mp3url");
    String body = element.getString("body");

    npTitle.setText(title);
    npDescription.setText(body);
    }
    else{
        npTitle.setText("Its null man");
        npDescription.setText("NULL POINTER EXCEPTION !");
    }
    return view;
}

当我点击FragmentA中的某个项目时,它会转到FragmentB随身携带的信息,如界面中所示,但所有这些都是FragmentA上的空白屏幕。请帮忙。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用抽象类来保存Object中的值。然后使用静态方法从任何其他类中获取值。