1

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

片段A.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();

}

片段B.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。请帮忙。

4

1 回答 1

1

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

于 2013-10-04T06:37:53.310 回答