使用ViewPager从父Activity调用Fragment的方法

时间:2015-06-24 23:47:42

标签: android android-fragments android-activity android-viewpager swipe

我有一些来自Slidenerd的Scrolltab视频系列的示例代码,这非常有效。但是,我不能从父活动中调用片段内的方法。例如,我在片段A中包含了一个名为doS​​omething()的方法。我想通过MainActivity的onResume()回调来调用它。

编辑: 使用"接受的答案"适用于此应用程序但不适用于由于nullpointerexception而我正在处理的实际应用程序。

错误日志

06-25 13:02:19.308    3862-3862/com.felhr.agweigh D/AndroidRuntime﹕ Shutting down VM
06-25 13:02:19.308    3862-3862/com.felhr.agweigh W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x416ecda0)
06-25 13:02:19.308    3862-3862/com.felhr.agweigh E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.felhr.agweigh, PID: 3862
    java.lang.RuntimeException: Error receiving broadcast Intent { act=com.felhr.usbservice.USB_PERMISSION_GRANTED flg=0x10 } in com.felhr.agweigh.MainActivity$3@41da2c10
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:782)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5479)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.felhr.agweigh.FragmentPlotCSV.createSpinner(FragmentPlotCSV.java:102)
            at com.felhr.agweigh.MainActivity$3.onReceive(MainActivity.java:894)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:772)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5479)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.felhr.agweigh" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.usb.host"
        android:required="true" />

    <application
        android:logo="@drawable/rinstrumlogo"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/RinstrumActionBarTheme" >
        <activity
            android:name="com.felhr.agweigh.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="com.felhr.agweigh.UsbService"
            android:enabled="true" >
        </service>

    </application>

</manifest>

MainActivity

public class MainActivity extends FragmentActivity {

ViewPager viewPager = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewPager = (ViewPager)findViewById(R.id.pager);
    FragmentManager fragmentManager = getSupportFragmentManager();
    viewPager.setAdapter(new MyAdapter(fragmentManager));
}

@Override
protected void onResume() {
    super.onResume();
}
}

MyAdapter

class MyAdapter extends FragmentPagerAdapter
{
public MyAdapter(FragmentManager fm)
{
    super(fm);
}

@Override
public Fragment getItem(int i) {
    Fragment fragment = null;
    Log.d("SWIPE","get Item is called"+i);
    if (i==0)
    {
        fragment=new FragmentA();
    }
    if (i==1)
    {
        fragment=new FragmentB();
    }
    if (i==2)
    {
        fragment=new FragmentC();
    }
    return fragment;
}

@Override
public int getCount() {
    Log.d("SWIPE","get count is called");
    return 3;
}

// talks to title to give the page
@Override
public CharSequence getPageTitle(int position) {
    if (position == 0) {
        return "Tab 1";
    }
    if (position == 1) {
        return "Tab 2";
    }
    if (position == 2) {
        return "Tab 3";
    }
    return null;
}
}

FragmentA

/**
 * Created by Luke on 20/04/2015.
 */
public class FragmentA extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }

    public void doSomething(){
        // call this method from main activity
        }
    }

FragmentB

/**
 * Created by Luke on 20/04/2015.
 */
public class FragmentB extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }
}

FragmentC

/**
 * Created by Luke on 20/04/2015.
 */
public class FragmentC extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }
}

2 个答案:

答案 0 :(得分:3)

只是一个问题,你的问题不是特定于使用ViewPager。

根据设计,除了FragmentA之外,活动对FragmentA一无所知,因此它不知道它包含doSomething()方法。快速而肮脏的方法是从适配器获取片段并在知道它是FragmentA时将其转换为FragmentA。我说这是一种“快速而肮脏”的方式,因为你想让事物在活动和片段之间分离 - 即。你的活动不应该知道你的FragmentA实现,只知道Fragment。

在构建更复杂的应用程序时,您需要考虑使用事件总线以分离的方式在片段和活动之间发送消息。这里有一些流行的Android事件总线: http://square.github.io/otto/ https://github.com/greenrobot/EventBus

答案 1 :(得分:2)

你可以这样做 -

    @Override
    protected void onResume() {
        super.onResume();
        FragmentA _fragA = new FragmentA();
        _fragA.doSomething();

    }

您可以使用以下元素在清单文件中注册接收器:

       <receiver android:name="MyReceiver" >
            <intent-filter>
                <action android:name="com.example.Broadcast" >
                    </action>
            </intent-filter>
        </receiver>

嵌套元素用于指定接收者应该响应的事件。