在Activity中调用Fragment方法

时间:2016-05-02 10:38:05

标签: java android android-fragments

我想在MainActivity中调用Fragment Method。 Fragment附加到我的MainActivity中的ViewPager

我在MainActivity中调用了该方法

mViewPager = (ViewPager) findViewById(R.id.pager);
        setupViewPager(mViewPager);

 private void setupViewPager(ViewPager mViewPager) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        mSectionsPagerAdapter.addFragment(new FeedsFragment(), "Around You");
        mSectionsPagerAdapter.addFragment(new InboxFragment(), "Shares");
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }      

 @Override
    public void onLocationChanged(Location location) {
       currentLocation = location;
        if (lastLocation != null
                && geoPointFromLocation(location)
                .distanceInKilometersTo(geoPointFromLocation(lastLocation)) < 0.01) {
            // If the location hasn't changed by more than 10 meters, ignore it.
            return;
        }
        lastLocation = location;
        if (!hasSetUpInitialLocation) {
            // Zoom to the current location.
            hasSetUpInitialLocation = true;
        }
                FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentById(R.id.feeds_fragment);
        if(fragment != null) {
            fragment.doFeedsQuery();
        }

    }

这是我的SectionsPagerAdapter

    protected Context mContext;
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {

        return mFragmentTitleList.get(position);
    }

}

这是我从片段中调用的方法

   public void doFeedsQuery() {
           Location myLoc = (MainActivity.currentLocation == null) ? MainActivity.lastLocation : MainActivity.currentLocation;
        // If location info is available, load the data
         if (myLoc != null) {
        // Refreshes the list view with new data based
        // usually on updated location data.
            feedsQueryAdapter.loadObjects();
         }
    }

这是我用

调用片段的资源ID
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/feeds_fragment"
    android:background="@color/white">

这是我的LogCat

java.lang.NullPointerException: Attempt to invoke virtual method 'void io.wyntr.peepster.Fragments.FeedsFragment.doFeedsQuery()' on a null object reference
                                                       at io.wyntr.peepster.Activities.MainActivity.onLocationChanged(MainActivity.java:687)
                                                       at com.google.android.gms.location.internal.zzk$zzb.handleMessage(Unknown Source)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:168)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5845)
                                                       at java.lang.reflect.Method.invoke(Native Method)

我不知道我哪里出错了。

4 个答案:

答案 0 :(得分:0)

初始化后,您只能调用片段的方法。

示例:

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();

Fragment yourFragment = new FeedsFragment();
fragmentTransaction.add(R.id.fragment_container, yourFragment);
fragmentTransaction.commit();

yourFragment.doFeedsQuery();

有很多关于此的文档,以及stackoverflow中的其他相关问题。

答案 1 :(得分:0)

你的问题似乎在这里:

   FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentById(R.id.feeds_fragment);

findFragmentById()将尝试查找id中指定的XML,但由于您使用的是动态方法,因此您没有 FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentByTag("Around You"); 。您应该使用的是findFragmentByTag,如下所示:

The format should be MAJOR.MINOR[FC]
FC is an optional suffix that indicates a forward compatible context. This is only valid for versions >= 3.0.
GL versions < 3.0 are set to a compatibility (non-Core) profile
GL versions = 3.0, see below
GL versions > 3.0 are set to a Core profile
Examples: 2.1, 3.0, 3.0FC, 3.1, 3.1FC
    2.1 - select a compatibility (non-Core) profile with GL version 2.1
    3.0 - select a compatibility (non-Core) profile with GL version 3.0
    3.0FC - select a Core+Forward Compatible profile with GL version 3.0
    3.1 - select a Core profile with GL version 3.1
    3.1FC - select a Core+Forward Compatible profile with GL version 3.1 
Mesa may not really implement all the features of the given version. (for developers only)

答案 2 :(得分:0)

请使用以下代码获取FeedsFragment片段的片段对象。

<?php 
if(isset($_POST['formSubmit'])){
echo '<pre>'.print_r($_POST,1).'</pre>';
}
?>

答案 3 :(得分:0)

针对您的问题的两种解决方案。创建片段的实例作为类成员,另一个已经由 Hiren Dabhi 告知。

static int a = 10;

并简单地检查它不是null并且isVisibleToUser然后调用你的方法

private FeedsFragment feedFragment;//Use as class instance.

private void setupViewPager(ViewPager mViewPager) {
        mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        mSectionsPagerAdapter.addFragment(feedFragment, "Around You");
        mSectionsPagerAdapter.addFragment(new InboxFragment(), "Shares");
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }