从活动中调用片段中的非静态方法?
我有一个活动,通过ViewPagerAdapter管理四个片段。 从我的活动,我想调用一个方法:从活动中调用片段中的非静态方法?
public void openButtons(){
//mPosition is a position of pager
if (mPosition==0){
Fragment1 fragment = (Fragment1) getSupportFragmentManager().findFragmentById(R.id.fragment1);
fragment.openButtons();
}
if (mPosition==1){
Fragment2 fragment = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.fragment2);
fragment.openButtons();
}
if (mPosition==2){
....
}
if (mPosition==3){
...
}
}
如果我的片段的方法定义为非静态:
public void openButtons(){//some stuff}
我得到一个fragment.openButtons空指针()行无论这个位置和片段如何。
如果该方法声明为静态,那没关系。
public static void openButtons(){//some stuff}
该方法的内容没有问题,因为问题与空方法相同。
所以我的问题是为什么我们必须在片段中定义静态方法?
“因为在这样的条件:
public void openButtons(){
//mPosition is a position of pager
if (mPosition==0){
Fragment1.openButtons()
}
if (mPosition==1){
Fragment2.openButtons()
}
if (mPosition==2){
....
}
if (mPosition==3){
...
}
}
同样的功能!
谢谢。
将null强制转换为引用不会将异常抛出到原始对象。
使用findFragmentById()或findFragmentByTag()来获取引用,并检查它是否为null,如果不是,则检查引用的isAdded()或isVisible()。
PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
if(p != null){
if(p.isAdded()){
p.onNotificationListener.updateUI();
}
}
我不明白你对链接的解释,该方法应该被称为静态? – Aristide13
它不是必需的方法是静态的。你必须调用片段方法,所以你必须检查片段不是空的,片段被添加和激活之后,你必须调用片段的方法。因此在上面的代码中,我必须检查所有这些条件 –
这正是我不明白的: NullPointer execption定位到该方法的情况下它不是静态的被视为null!所以为什么我没有空指针: Fragment1 fragment =(Fragment1)getSupportFragmentManager()findFragmentById(R.id.fragment1)。 当方法是静态的,反之亦然,当方法不是静态的! 另外在你的代码中的函数:onNotificationListener? 非常感谢您的帮助... – Aristide13
因此,在viewPager的情况下 ,找到其ID或代码片段的情况下,是不正确的方法。
这是更好地做到以下几点:
public void openButtons() {
// mPosition is a position of pager
ViewPagerAdapter adapter = ((ViewPagerAdapter) mViewPager.getAdapter());
if (mPosition == 0) {
Fragment fragment = adapter.getItem(0);
((Fragment1)fragment).openButtons();
}
if (mPosition == 1){
Fragment fragment = adapter.getItem(1);
((Fragment2)fragment).openButtons();
}
if (mPosition == 2){
....
}
if (mPosition == 3){
...
}
}
留言Merci。
你为什么不做一个特定片段的静态对象引用?并与该obj你设法调用片段中的任何方法。不需要定义静态方法。 – user3819810
请参阅[此链接](http://stackoverflow.com/questions/10903077/calling-a-fragment-method-from-a-parent-activity)可能会帮助你。 – Pankaj
'getSupportFragmentManager()。findFragmentById(R.id.fragment1);'return null? – Altoyyr