简体   繁体   English

在Activity中调用Fragment方法

[英]Calling Fragment Method in Activity

I want to call Fragment Method in my MainActivity.我想在我的 MainActivity 中调用 Fragment 方法。 The Fragment is attached to ViewPager in my MainActivity Fragment 附加到我的 MainActivity 中的 ViewPager

I have called the method in my MainActivity我在 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();
        }

    }

This my SectionsPagerAdapter这是我的 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);
    }

}

This is the method I am calling from my Fragment这是我从 Fragment 调用的方法

   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();
         }
    }

This is the resource id I am calling the fragment with这是我调用片段的资源 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">

Here is my LogCat这是我的 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)

I don't know where I have gone wrong.我不知道我哪里出错了。

You can only call a fragment's method after you have initialized it. 初始化片段后,只能调用它的方法。

Example: 例:

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

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

yourFragment.doFeedsQuery();

There's plenty of documentation over this, and other related questions in stackoverflow. 有很多关于此的文档,以及stackoverflow中的其他相关问题。

Your problem seems to be here: 您的问题似乎在这里:

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

findFragmentById() will try to find the id specified in XML and you don't have one since you're using a dynamic approach. findFragmentById()将尝试查找XML指定的id ,由于使用了动态方法,因此您没有id What you should use instead is findFragmentByTag like this: 您应该使用的是findFragmentByTag,如下所示:

 FeedsFragment fragment = (FeedsFragment) getSupportFragmentManager().findFragmentByTag("Around You");

Please use below code get fragment object of FeedsFragment fragment. 请使用下面的代码获取FeedsFragment片段的fragment对象。

    int size = mSectionsPagerAdapter.getCount();
    for (int i = 0; i < size; i++) {
        Fragment fragment = mSectionsPagerAdapter.getItem(i);
        if (fragment != null && fragment instanceof FeedsFragment) {
            ((FeedsFragment)fragment).doFeedsQuery();
        }
    }

Two solutions for your problem. 针对您的问题的两种解决方案。 create Instance of your fragment as class Member and the other already told by Hiren Dabhi . 创建类成员的片段实例, Hiren Dabhi已经告诉另一个实例。

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);
    }  

and simply check it's not null and isVisibleToUser then call your method 并简单地检查它是否不为null和isVisibleToUser然后调用您的方法

if(feedFragment != null && feedFragment.isVisible())
  feedFragment.doFeedsQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM