需要幫助,試圖調用Activity的方法片段,我認爲這是不正確的請求標記片段。NullPointerException調用標記片段ViewPager
這麼問標籤:
public class TitleAdapter extends FragmentPagerAdapter {
public final String titles[] = new String[] { "A", "B", "C" };
public final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
fm.beginTransaction().add(frags[0], "fragA").commit();
frags[1] = new FragmentB();
fm.beginTransaction().add(frags[1], "fragB").commit();
frags[2] = new FragmentC();
fm.beginTransaction().add(frags[2], "fragC").commit();
}
@Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
@Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
@Override
public int getCount() {
return frags.length;
}
}
感受到引起的onCreate(捆綁savedInstanceState)右
public class MainActivity extends FragmentActivity {
TitleAdapter titleAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
FragmentManager fm = getSupportFragmentManager();
FragmentA fragment = (FragmentA)fm.findFragmentByTag("fragA");
fragment.bgStop();
這裏的方法本身
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
static Button btnPlay;
public FragmentA() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
btnPlay = (Button) rootView.findViewById(R.id.btnStart);
return rootView;
}
public void bgPlay(){
btnPlay.setText("Play");
btnPlay.setBackgroundResource(R.drawable.play_button);
}
public void bgStop(){
btnPlay.setText("Stop");
btnPlay.setBackgroundResource(R.drawable.stop_button);
}
}
你必須定義兩次TitleAdapter titleAdapter參考。刪除其中的任何一個。 –
你有關這兩條記錄? TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());和FragmentManager fm = getSupportFragmentManager(); – user3064772
主要活動後沒有。以及你得到NUll指針異常的地方。 –