我試圖在viewpager中的兩個片段之間傳遞字符串,但我沒有找到正確的方法來做到這一點。 這是到目前爲止我的代碼:如何在viewpager中的片段之間傳遞字符串
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 6;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new MyFragment();
case 1:
return new part2();
case 2:
return new Part3();
case 3:
return new Part4();
case 4:
return new Part5();
case 5:
return new Part6();
default:
return null;
}
}
/** Returns the number of pages */
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
return "Page #" + (position + 1);
}
}
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
我不使用標籤與viewpager。我應該在碎片中寫什麼?
UPDATE: 我試圖實現一個接口等提出的答案:
public interface OnTogglePressListener {
public void onTogglePressed(String msg);
}
在第一片段:
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
try {
buttonListener = (OnTogglePressListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onTogglePressed");
}
super.onAttach(activity);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
buttonListener.onTogglePressed("Off");
... }
在第二片段:
public String getEtat(String etat)
{ state =etat;
return etat;
}
在ma in activity:
public void onTogglePressed(String etat)
{
Part5 p = (Part5)getSupportFragmentManager().findFragmentById(R.layout.frag_2);
p.getEtat(etat);
}
但是我每次都得到一個NullPointerException。
你初始化了你的接口嗎?嘗試從你的接口創建一個對象,然後在onActivityCreated()回調函數上實例化你的接口對象,如:InterfaceInstance =(onTogglePressListener)getActivity(); –
之後? – user2137817