要值傳遞給另一個片段我有我的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();
}
破片mentB.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
一個空白屏幕。請幫忙。
代碼看起來沒問題。你究竟得到NullPointerException的哪一行? –
@GaneshBhambarkar其實不是一個NullPointerException ... FragmentA在點擊時變成空白。當試圖去FragmentB,那就是我在'Bundle element = this.getArguments()' –
'上得到NullPointerException異常。試着在你的FragmentB中getActivity.getArguments()的上下文中獲得Bundle值 – GrIsHu